3M

Java Swing and Advanced Developer

Advanced Swing Components

______

Swing

Swing is a GUI toolkit for Java. It is one part of the Java Foundation Classes (JFC). Swing includes graphical user interface (GUI) widgets such as text boxes, buttons, split-panes, and tables.

Swing widgets provide more sophisticated GUI components than the earlier Abstract Window Toolkit. Since they are written in pure Java, they run the same on all platforms, unlike the AWT which is tied to the underlying platform's windowing system. Swing supports pluggable look and feel – not by using the native platform's facilities, but by roughly emulating them. This means you can get any supported look and feel on any platform.

The disadvantage of lightweight components is slower execution. The advantage is uniform behavior on all platforms. *

* Wikipedia

Where can I get more resources on Swing GUI?

Sun provides links for tutorials on various Swing components.

http://java.sun.com/docs/books/tutorial/uiswing/examples/components/index.html

They provide files ready to run in Netbeans IDE. They can all be adapted to run on other IDEs as well in editors such as EditPlus, or even command line.

http://java.sun.com/docs/books/tutorial/information/examples.html

Bundles of Current Material which are updated to keep up with new Java releases

http://java.sun.com/docs/books/tutorial/information/download.html#egs

Bundle / Compressed /
Uncompressed / HTTP Download
Online Tutorial
(last updated April 30, 2007) / 26.2 MB / 49.6 MB / tutorial.zip
Tutorial Examples
(Not including the Swing Tutorial examples;
last updated April 30, 2007) / 1.2 MB / 2.5 MB / tut-examples.zip
Swing Trail
(Including the Swing Tutorial Examples;
last updated April 30, 2007) / 28.3 MB / 39.6 MB / tut-swing.zip
Swing Tutorial Examples
(last updated April 30, 2007) / 3.4 MB / 21.9 MB / SwingTutorialExamples.zip*

Java Programs Types

Applications

Applications run on the client machine and have all rights to the resources of the computer as any other programs in any language

Applets

Applets are resident on the server and are downloaded in bytecode to the client machine. Applets are real Java programs which run in the browser environment. They have the capability to communicate to their browser context. The applet runs in a sandbox by default. It has restrictions to the machine resources, such as the local file system, peripherals, and networking ability.

Servlets

Servlets are Java programs which execute in the Web Server (container) environment. The can take parameters and have no restrictions. They have no GUI and typically their output stream is sent to the client program (typically, but not always a browser). These are commonly used in web applications.

Midlets

Midlets are Java programs written to execute on small PDAs, such as cell phones with a JVM installed. To write a MIDlet, you can get the JWT (Java Wireless Toolkit) or an IDE such as Netbeans with the NetBeans Mobility Pack.

Java Programs Types

Web Applications

Web Applications are a client server relationship, where the client connects to the web server through the HTTP protocol. The request typically carries some information about the client request, often user name, account, or password.

The web server response is sent back to the browser with objects that the typical browser can understand, HTML, Javascript, Applets, Flash, . . .

Since the HTTP protocol is connectionless in nature a request/response sequence terminates the connection. A client must issue another request to get further information. In order not to lose information about the client’s last connection, web servers use a session ID. This is nothing more than a header field sent back from the server after the initial communication sequence. The client’s browser will sent that header along with any other information to the server. This helps the server to keep track of the status or state of the connection.

Web applications are really system applications, which are open many concurrent users. Because the client request often travel and navigates through pages over many consecutive communications, web apps have variables to keep track of the application state on the user, and the global level (for all users). Web apps can create and access objects to keep track of the application state using a variety of scopes. These include page, request, session, and application.

Java technology, which facilitates these web applications, is strongly based on Servlets and JSPs (Java Server Pages). Servlets and JSPs run entirely in the server, have no restrictions on access of resources, and can communicate to their context (the web applications). The present no GUI so what is rendered to the client is done with HTML and Javascript. These codes are often generated as output and streamed to the client machine.

GUI Choices in Distributed Applications

Client Applications

Client Applications can be Swing , AWT or SWT GUI programs. The can be installed on the client, downloaded and executed by an automated system (such as JNLP using Java Web Start), or download as Jar or Installation file manually by the user of the client machine.

Applets

Applets can have a full GUI just as Client Applications, they have the advantage of being run on thin clients, and can be modified in a central place without client machine modification. Their restriction is the sandbox and this can be overcome with modification of permissions on the client machine or through a signing mechanism.

Web Applications

Web Applications are strong in processing power, as the infrastructure is solid for backend processing. GUI is the weakest and least integrated part of this type of application. One choice is to use HTML or even DHTML (HTML, Javascript, CSS, DOM). These techniques are unsatisfying or at least not as integrated and flexible as a real GUI environment.

Solution choices include using

1.  Applets as part of the presentation

2.  JSF technology

3.  JNLP

4.  GWT

Java Swing Components

Swing Design Goal

To build a set of extensible GUI components to enable developers to more rapidly develop powerful Java front ends for commercial applications.

How it was achieved

  1. Be implemented entirely in Java to promote cross-platform consistency and easier maintenance.
  2. Provide a single API capable of supporting multiple look-and-feels so that developers and end-users would not be locked into a single look-and-feel.
  3. Enable the power of model-driven programming without requiring it in the highest-level API.
  4. Adhere to Java Beans design principles to ensure that components behave well in IDEs and builder tools.
  5. Provide compatibility with AWT APIs where there is overlapping, to leverage the AWT knowledge base and ease porting.

Swing MVC – Model View Controller Architecture

A model that represents the data for the application.

The view that is the visual representation of that data.

A controller that takes user input on the view and translates that to changes in the model.

Swing MVC – Model View Controller Architecture

The real Swing architecture is more like shown below.

Separable Model Architecture

The V and C parts are the component and the UI object. The UI object’s parts need to be tightly integrated.

Separable Model Architecture (SMA)

Each Swing component has a separate model component for a swing component. Default models exist, but can be customized for any Swing class. Some examples are shown below.

Component / Model Interface / Model Type
JButton
/
ButtonModel
/ GUI
JToggleButton / ButtonModel / GUI/data
JCheckBox / ButtonModel / GUI/data
JTabbedPane / SingleSelectionModel / GUI
JList / ListModel / data
JList / ListSelectionModel / GUI
JTable / TableModel / data
JTable / TableColumnModel / GUI
JTree / TreeModel / data
JTree / TreeSelectionModel / GUI

SMA Architecture Model Independence

Swing Renderers

A renderer is a Swing helper class to help the JVM create the visual aspect of a swing component. Classes that contain collections of components allow the programmer to describe how elements in these collections should be displayed.

The content object may be a String or some other class, while the render my display it as a JLabel, JButton, JComboBox or something else.

Think what you see as a representation of what is actually there.

A Swing Renderer for a JTable (inner class)

class TimeTableRenderer extends JLabel implements TableCellRenderer {

private TableCellRenderer defaultRenderer;

private Font font = new Font("Helvetica", Font.BOLD, 10);

public TimeTableRenderer() {

setOpaque(true); setFont(font); setHorizontalAlignment(SwingConstants.CENTER);}

public Component getTableCellRendererComponent (JTable table, Object value,

boolean isSelected, boolean hasFocus, int row, int column) {

if (table.getRowCount() == 0)

return null;

if (value.toString().equals("")) {

setBackground(Color.black);

Border b = BorderFactory.createEmptyBorder();

this.setBorder(b); }

else {

if (Integer.parseInt(((String)value).substring(0,2)) % 2 == 0) {

setBackground(Color.blue);

setForeground(Color.white); }

else {

setBackground(Color.yellow);

setForeground(Color.black); }}

if (value == null) { setText(""); setToolTipText(""); }

else { setText(value.toString()); setToolTipText(value.toString()); }

if (isSelected) { setBackground(Color.blue); }

repaint();

return this; }}

Renderer in Table changed from JLabel to JButton *

* UI also changed from Metal to Windows

Swing Renderer and Editor Access

TableModel (interface)

Default TableModel (implementing class)

TableColumnModel (interface)

DefaultTableColumnModel (implementing class)

TableColumn (class)

Swing Custom Editor (inner class)

class MyTableCellEditor2 extends AbstractCellEditor implements TableCellEditor {

JComponent component = new JTextField();

// This method is called when a cell value is edited by the user.

// 'value' is value contained in the cell located at (row, col)

public Component getTableCellEditorComponent(JTable table, Object value,

boolean isSelected, int row, int col) {

// Configure the component with the specified value

((JTextField)component).setText((String) value);

component.setBackground(Color.orange);

component.setForeground(Color.RED);

// Return the configured component

return component; }

// Called when editing is completed.

// Returns the new value to be stored in the cell.

public Object getCellEditorValue() {

return ((JTextField) component).getText(); }}

Swing Custom Editor

Swing Abstract and Default Classes

Swing Components – JList

JList Constructors

JList()

JList(ListModel)

JList(Object[])

JList(Vector)

JList DefaultListModel

JList Example

Reading and listing files from a user chosen directory

JList Program Listing

import java.awt.*;

import javax.swing.*;

import java.io.*;

import java.awt.event.*;

public class JListDirectory extends JFrame {

private String directoryName;

public JListDirectory () {

super("File Listing w/ JList");

setSize(400,400);

setLocation(300,300);

setVisible(true);

addWindowListener(new WindowAdapter() {

public void windowClosing(WindowEvent e) { System.exit(0); } });

JFileChooser chooser = new JFileChooser();

// Allows choosing of directories only, not ordinary files

chooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);

int option = chooser.showOpenDialog(this);

if (option == JFileChooser.APPROVE_OPTION) {

if (chooser.getSelectedFile()!= null){

directoryName = chooser.getSelectedFile().getAbsolutePath(); }}

File selectedDirectory = new File(directoryName);

File [] files = null;

if(selectedDirectory.isDirectory()) files = selectedDirectory.listFiles();

else {

System.err.println("Not a Directory Selected! Program exiting.");

System.exit(0); }

JList Program Listing (continued)

JList fileList = new JList(files); // JList takes Object [] as elements

fileList.setVisibleRowCount (8);

JScrollPane pane = new JScrollPane (fileList);

this.getContentPane().add(pane, BorderLayout.CENTER);

validate(); }

public static void main(String [] s) {

EventQueue.invokeLater(new Runnable() {

public void run() { new JListDirectory(); }});

}}

Try It Out

First off, run the code in the JList directory in the labs section. Make a project ion Eclipse with the JListDirectory file. Your program should look similar to the one on page 22.

Your assignment is to make a new renderer for the JList so that each file will be displayed with just the file name without the full path prefix. Also each file name should be displayed as a JLabel in alternating colors blue/yellow (see below).

1.  You will need to write a class that extends the DefaultListCellRenderer, call it MyJListRenderer.

2.  You will need to override the

getListCellRendererComponent(JList, Object, int, boolean, boolean)

method. The method has to take the value (Object parameter) and use String methods to return the string following the last subdirectory “/” character. Also it will return a JLabel as a rendering with the new string as its text. Based upon the index of the element, color the JLabel yellow or blue in odd/even alternating fashion.

Swing JComboBox

The JComboBox is a list item selector, which can optionally allow for simple addition into its list of items.

The DefaultComboBoxModel has the following constructors

DefaultComboBoxModel()

DefaultComboBoxModel(Object[] items)

DefaultComboBoxModel(Vector v)

The methods for this class are

void addElement(Object anObject)

Object getElementAt(int index)

int getIndexOf(Object anObject)

Object getSelectedItem()

int getSize()

void insertElementAt(Object anObject, int index)

void removeAllElements()

void removeElement(Object anObject)

void removeElementAt(int index)

void setSelectedItem(Object anObject)

Swing JComboBox

Swing JTree

A JTree is a very flexible component used for navigating hierarchical structures. A common usage is for directories or for XML files using the hierarchical DOM model.

The Trees application is a simple example of using this component.

Swing JTree

The JTree is easily created and manipulated by the DefaultMutableTreeNode class.

Here is the code listing

This class builds a subtree from a string array. The returned tree is rooted at the node labeled by the first string, and the remaining strings are used as the labels for the children of the root. It is a non-public class contained in the same file as the public Trees class.

import java.awt.*;

import java.awt.event.*;

import javax.swing.*;

import javax.swing.tree.*;

class Branch {

DefaultMutableTreeNode r;

public Branch(String[] data) {

r = new DefaultMutableTreeNode(data[0]);

for(int i = 1; i < data.length; i++) {

DefaultMutableTreeNode node = new DefaultMutableTreeNode(data[i]);

r.add(node); } }

public DefaultMutableTreeNode getNode() { return r; }}

Swing JTree

public class Trees extends JPanel {

String[][] data = {

{ "Trees", "Maple", "Oak", "Larch","Chestnut" },

{ "Colors", "RED", "GREEN", "BLUE","YELLOW","MAGENTA" },

{ "Names","Joseph","Julius","Fred","Sandy","Benjamin"},

{ "Fonts","Helvetica","Courier","Arila","Times","Gothic"}};

static int i = 0;

DefaultMutableTreeNode root, child, chosen;

JTree tree;

DefaultTreeModel model;

public Trees() {

setLayout(new BorderLayout());

root = new DefaultMutableTreeNode("The Root");

tree = new JTree(root);

// Use a scrollpane as a container:

add(new JScrollPane(tree), BorderLayout.CENTER);

// Capture the tree's model:

model =(DefaultTreeModel)tree.getModel();