




































































Study with the several resources on Docsity
Earn points by helping other students or get them with a premium plan
This page cannot be seen from the preview
Don't miss anything!





































































Advanced Swing Components
Objectives
Introduction
In the preceding three chapters, you learned how to use Swing components, containers, layout managers, menus, tool bars, and dialog boxes. This chapter will show you how to work with some of the complex Swing components. You will learn how to use JList, JComboBox, JTable, and JTree to create advanced graphical user interfaces.
JList
A list is a component that enables you to choose one or more items. It is useful in limiting a range of choices and avoids the cumbersome validation of data input. JList is the Swing version of list. Functionally it is similar to a set of check boxes or radio buttons, but the selectable items are placed in a list and are chosen by clicking on the items themselves. Figure 8.1 shows an example of JList.
Figure 8.
SwingSet2 demonstrates the features of JList.
JList doesn't support scrolling directly. To create a scrollable list, you need to create a JScrollPane and add an instance of JList to the scroll pane. An instance of JList can be created using its default constructor or one of the following three constructors:
JList generates javax.swing.event.ListSelectionEvent to notify the listeners of the selections. The listener must implement the valueChanged handler to process the event.
Example 8.1 Simple List Demo
This example creates a list of a fixed number of items displayed as strings. The example allows you to set a selection mode dynamically from a combo box, as shown in Figure 8.2. When you select an item or multiple items, the item values are displayed in a status label below the list.
Figure 8.
You can choose single selection, single-interval selection, or multiple-interval selection in a list.
Here are the steps to complete the project:
to the center of the applet, and drop a JList to the scroll pane to create jList1. Drop a JLabel to the south of the applet to create jlblStatus.
jList1.setListData(countries);
Listing 8.1: TestList.java
package listdemo;
import java.awt.; import java.awt.event.; import javax.swing.; import javax.swing.event.;
public class TestList extends JApplet { boolean isStandalone = false; JScrollPane jScrollPane1 = new JScrollPane(); JList jList1 = new JList();
JPanel jpSelectionMode = new JPanel(); JComboBox jcboSelectionMode = new JComboBox(); JLabel jlblStatus = new JLabel();
JLabel jLabel1 = new JLabel(); BorderLayout borderLayout1 = new BorderLayout();
// Create an array of strings for country names String[] countries = {"United States", "United Kingdom", "China", "Germany", "France", "Canada"};
/*Initialize the applet/ public void init() { try {
/*Handle item selection in the list/ void jList1_valueChanged(ListSelectionEvent e) { int[] indices = jList1.getSelectedIndices(); Object[] selectedItems = jList1.getSelectedValues(); String display = "";
for (int i=0; i<indices.length; i++) { display += (String)selectedItems[i] + " "; }
jlblStatus.setText(display); } }
Example Review The program creates an array of strings and sets the array as listData in the list. The list is placed in a scroll pane so that you can scroll it when the number of items in the list exceeds the viewing area.
When the user selects an item in the list, the valueChanged handler is executed, which gets the selected items and displays all the items in the label.
The example enables you to specify selection mode from a combo box. When you choose SINGLE_SELECTION, only one item can be selected at a given time. When you choose SINGLE_INTERVAL_SELECTION, multiple consecutive items can be selected all together by holding down the SHIFT key. When you choose MULTIPLE_INTERVAL_SELECTION, you can choose any number of items anywhere in the list by holding down the CTRL key.
List Models
The previous example constructs a list with a fixed set of strings. If you want to add new items or delete existing items from the list, you have to use a list model. This section introduces list models.
The JList class delegates the responsibilities of storing and maintaining data to its data model. The JList class itself does not have the methods for adding or removing items from the list. These methods are supported in the list model.
All list models implement the ListModel interface, which defines the registration methods for ListDataEvent. The instances of ListDataListener are notified when the items in the list are modified. ListModel also defines the methods getSize and getElementAt. The getSize method returns the length of the list, and the getElementAt method returns the element at the specified index.
AbstractListModel implements the ListModel and Serializable interfaces. AbstractListModel implements the registration methods in the ListModel, but does not implement the methods getSize and getElementAt.
DefaultListModel extends AbstractListModel and implements the two methods getSize and getElementAt, which are not implemented by AbstractListModel. The relationship among ListModel, AbstractListModel, and DefaultListModel is shown in Figure 8.3.
ListModel
getElementAt(index: int): Object getSize(): int addListDataListener(l: ListDataListener): void removeListDataListener(l: ListDataListener)
AbstractListModel
DefaultListModel
+add(index: int, element: Object): void +addElement(element: Object): void +capacity(): int +clear(): void +contains(element: Object): boolean +copyInto(anArray: Object[]): void +elementAt(index: int): void +elements():Enumeration +ensureCapacity(minCapacity: int): void +firstElement():Object +get(index: int): Object +getElementAt(index: int): Object +getSize():int +indexOf(element: Object): int +indexOf(element: Object, index: int): int +insertElementAt(obj: Object, index: int): void +isEmpty(): boolean +lastElement():Object +lastIndexOf(element: Object): int +lastIndexOf(element: Object, index: int): int +remove(index: int): Object +removeAllElements():void +removeElement(obj: Object): boolean +removeElementAt(index: int): void +removeRange(fromIndex: int, toIndex: int): void +set(index: int, element: Object): Object +setElementAt(obj: Object, index: int): void +setSize(newSize: int): void +size():int +toArray():Object[] +trimToSize(): void
Figure 8.
DefaultListModel is a concrete implementation of ListModel.
The methods in DefaultListModel are similar to those in the java.util.Vector class. You use the add method to insert an element to the list, use the remove method to remove the element from the list, use the clear method to clear the list, and use the getSize method to return the number of elements in the list, and the getElementAt method to retrieve an element. In fact, the DefaultListModel stores data in an instance of Vector, which is essentially a resizable array. Swing components were developed
Listing 8.2: TestListModel.java
package listdemo;
import java.awt.; import java.awt.event.; import javax.swing.; import javax.swing.event.;
public class TestListModel extends JApplet { boolean isStandalone = false; JScrollPane jScrollPane1 = new JScrollPane(); JList jList1 = new JList(); JPanel jpSettings = new JPanel(); JLabel jLabel1 = new JLabel(); JTextField jtfNewItem = new JTextField(); JButton jbtAdd = new JButton(); JButton jbtRemove = new JButton(); JPanel jpAdd = new JPanel(); JPanel jpRemove = new JPanel(); JComboBox jcboSelectionMode = new JComboBox(); BorderLayout borderLayout1 = new BorderLayout(); BorderLayout borderLayout2 = new BorderLayout(); BorderLayout borderLayout3 = new BorderLayout(); JLabel jlblStatus = new JLabel(); JLabel jLabel2 = new JLabel();
// Create a list model DefaultListModel listModel = new DefaultListModel();
/*Initialize the applet/ public void init() { try { jbInit(); } catch(Exception e) { e.printStackTrace(); } }
/*Component initialization/
private void jbInit() throws Exception { this.setSize(new Dimension(400, 300)); jLabel1.setText("Enter a New Item"); jbtAdd.setText("Add New Item"); jbtAdd.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(ActionEvent e) { jbtAdd_actionPerformed(e); } }); jbtRemove.setText("Remove Selected Item"); jbtRemove.addActionListener( new java.awt.event.ActionListener() { public void actionPerformed(ActionEvent e) { jbtRemove_actionPerformed(e); } });
jList1.setModel(listModel); jList1.addListSelectionListener( new javax.swing.event.ListSelectionListener() { public void valueChanged(ListSelectionEvent e) { jList1_valueChanged(e); } }); jpAdd.setLayout(borderLayout1); jpSettings.setLayout(borderLayout2); jpRemove.setLayout(borderLayout3); jcboSelectionMode.addActionListener( new java.awt.event.ActionListener() { public void actionPerformed(ActionEvent e) { jcboSelectionMode_actionPerformed(e); } }); jlblStatus.setText("Status"); jLabel2.setText("Choose Selection Mode"); this.getContentPane().add(jScrollPane1, BorderLayout.CENTER); jScrollPane1.getViewport().add(jList1, null); this.getContentPane().add(jpSettings, BorderLayout.NORTH); jpSettings.add(jpRemove, BorderLayout.SOUTH); jpRemove.add(jcboSelectionMode, BorderLayout.CENTER); jpRemove.add(jbtRemove, BorderLayout.EAST); jpRemove.add(jLabel2, BorderLayout.WEST); jpSettings.add(jpAdd, BorderLayout.NORTH); jpAdd.add(jLabel1, BorderLayout.WEST); jpAdd.add(jtfNewItem, BorderLayout.CENTER); jpAdd.add(jbtAdd, BorderLayout.EAST); this.getContentPane().add(jlblStatus, BorderLayout.SOUTH);
// Add items to the list model listModel.addElement("United States"); listModel.addElement("United Kingdom"); listModel.addElement("China"); listModel.addElement("Germany"); listModel.addElement("France");
in the list. The model enables you to add and remove items in the list,
To add an element, the user enters the new element in the text field, and clicks the Add New Item button to add the element to the model. The model notifies the list's UI delegate to display the new element in the list.
To remove elements, the user specifies a selection mode, selects the elements, and clicks the Remove Selected Item to remove the item(s) from the model. The getSelectedIndices() method returns the indices of all selected items in strict order. Whenever an item is removed from the list, the indices of the items are immediately rearranged. Thus, the current index of i th item to remove is selectedIndices[i] - i, as shown in Listing 8.2.
List Selection Models
Unlike most Swing components, JList has two models: a list model and a list selection model. List models handle data management, and list selection models deal with data selection. A list selection model must implement the ListModelSelection interface, which defines constants for three selection modes (SINGLE_SELECTION, SINGLE_INTERVAL_SELECTION, and MULTIPLE_INTERVAL_SELECITON), and registration methods for ListSectionListener. It also defines the methods for adding and removing selection intervals, and the access methods for the properties, such as selectionMode, anchorSelectionIndex, leadSelectionIndex, and valueIsAdjusting.
By default, an instance of JList uses DefaultListSelectionModel, which is a concrete implementation of ListSelectionModel. Usually, you do not need to provide custom list selection model, because the DefaultListSelectionModel class is sufficient in most cases. Unlike the list data model, you do not need to access the list selection model directly, because most of the methods you need from the list selection model are also defined in Jlist.
List Cell Renderers
The previous example displays items as strings in a list. JList is very flexible and versatile, and it can be used to display images and drawings in addition to simple text. This section introduces list cell renderers for displaying graphics.
In addition to delegating data storage and processing to list models, JList delegates the rendering of the list cells to list cell renderers. All list cell renderers implement the ListCellRenderer interface, which defines a single method getListCellRendererComponent as follows:
public Component getListCellRendererComponent (JList list, Object value, int index, boolean isSelected, boolean cellHasFocus)
This method is passed with a list, the value associated with the cell, the index of the value, and the information regarding whether the value is selected and the cell has the focus. The component returned from the method is painted on the cell in the list.
By default, JList uses DefaultListCellRenderer to render its cells. The DefaultListCellRenderer class implements ListCellRenderer, extends JLabel, and can display either a string or an icon, but not both in the same cell. You can create custom renderer by implementing ListCellRenderer.
Example 8.3 List Cell Renderer Demo
This example creates a list of countries and displays the country flag and the country name in the list, as shown in Figure 8.5. When a country is selected in the list, its flag is displayed in a panel next to the list.
Figure 8.
The image and the text are displayed in the list cell.
The program requires a custom list cell renderer to display an image and a text in the same cell. Often you need to create a new list model that provides additional information for rendering the cell. In this example, each item has an image and a label, which should be stored in the list model for use by the list cell renderer as well as by the users of the list. The new list model named MyListModel is given in Listing 8.3.
Listing 8.3: MyListModel.java
Border emptyBorder = BorderFactory.createEmptyBorder(2, 2, 2, 2);
public MyListCellRenderer() { listCellPanel.setOpaque(true); jlbl.setPreferredSize(new Dimension(100, 60)); listCellPanel.setLayout(new BorderLayout()); listCellPanel.add(imageViewer, BorderLayout.CENTER); listCellPanel.add(jlbl, BorderLayout.EAST); }
/*Implement this method in ListCellRenderer/ public Component getListCellRendererComponent (JList list, Object value, int index, boolean isSelected, boolean cellHasFocus) { MyListModel listModel = (MyListModel)list.getModel(); String country = listModel.getName(value); Image image = listModel.getImage(value); jlbl.setText(country); imageViewer.setImage(image);
if (isSelected) { listCellPanel.setForeground(list.getSelectionForeground()); listCellPanel.setBackground(list.getSelectionBackground()); } else { listCellPanel.setForeground(list.getForeground()); listCellPanel.setBackground(list.getBackground()); }
if (cellHasFocus) listCellPanel.setBorder(lineBorder); else listCellPanel.setBorder(emptyBorder);
return listCellPanel; } }
The MyListCellRenderer class implements the getListCellRendererComponent method in the ListCellRenderer interface. The getListCellRendererComponent method obtains the list model of list, and obtains the name and image of the cell value through the list model. It then displays the image in an image panel and the name in a label. The image panel and the label are placed in a panel (listCellPanel) that is the returned component of the getListCellRendererComponent method.
The ImageViewer class for displaying an image was presented in Example 4.1, “Creating an Image Viewer.”
Finally, let us construct the main program that utilizes the custom list model and custom list cell renderer in a list. Here are the steps to complete the project:
Listing 8.5: TestListCellRenderer.java
package listdemo;
import java.awt.; import java.awt.event.; import java.applet.; import javax.swing.; import javax.swing.event.*; import imageviewerdemo.ImageViewer;
public class TestListCellRenderer extends JApplet { boolean isStandalone = false; JSplitPane jSplitPane1 = new JSplitPane(); JScrollPane jScrollPane1 = new JScrollPane(); JList jList1 = new JList(); ImageViewer imageViewer1 = new ImageViewer();
MyListModel listModel;
// Create a list cell renderer ListCellRenderer myListCellRenderer = new MyListCellRenderer();
/*Initialize the applet/ public void init() { try { jbInit(); } catch(Exception e) { e.printStackTrace(); }
/*Handle list selection event/ void jList1_valueChanged(ListSelectionEvent e) { Image image = listModel.getImage(jList1.getSelectedValue()); imageViewer1.setImage(image); } }
Example Review The example consists of four classes: MyListModel, MyListCellRenderer, ImageViewer, and TestListCellRenderer. The MyListModel class is responsible for storing data that includes image and text for the list. The MyListCellRenderer class is responsible for rendering the cell with image and text. The ImageViewer class displays an image in the panel. The TestListCellRenderer class tests the list with the custom list cell renderer.
When you choose a country in the list, the list selection event handler is invoked. This handler obtains the list model for the list, uses the list model to retrieve the country's flag image, and displays the image in the image panel on the right side of the split pane.
The getListCellRendererComponent method in MyListCellRenderer is passed with parameters list, value, index, isSelected, and isFocused. The list is used to obtain the list model. The value determines the image and name of the country displayed in the cell. If the cell is selected, the background and foreground of the cell are set to the list's selection background and foreground. If the cell is focused, the cell's border is set to the line border; otherwise, it is set to the empty border. The empty border serves as divider between the cells.
NOTE: The images may not be displayed immediately, because it takes time to load them. You can use image tracker techniques to ensure that the images are loaded before they are displayed. Tracking loading images is introduced in Chapter 16, "Multimedia," in my Introduction to Java Programming with JBuilder 4 book.
TIP: The label’s preferred size is set to 100 by 60 in the MyListCellRenderer class so it will be limited to 100 by 60 and the rest of the space in the cell renderer is allocated to the image.
JComboBox
A combo box is a component similar to a list. Both combo box and list are used for selecting items from a list. A combo box allows the user to select one item at a time, while a list permits multiple selections. A combo box displays a drop-down list contained in a popup menu when the combo box is clicked. The selected item can be edited in the cell as if it were a text field.
The constructors of JComboBox are similar to those of JList. An instance of JComboBox can be created using its default constructor or one of the following three constructors:
The following properties of JComboBox are often useful:
Like JList, the JComboBox class delegates the responsibilities of storing and maintaining data to its data model. All combo box models implement the ComboBoxModel interface, which extends the ListModel interface and defines the getSelectedItem and