Docsity

Java Programming Applets and JTree Components - Prof. Y. Daniel Liang, Study Guides, Projects, Research of Computer Science

Toggle sidebar
bg1
8
Advanced Swing Components
Objectives
• Use JList to select single or multiple items in a list.
• Use JComboBox to select a single item from a combo box.
• Use JTable to display and process tables.
• Use JTree to display data in a tree hierarchy.
• Learn how to create custom renderers for JList, JComboBox,
JTable, and JTree.
• Learn how to create custom editors for JComboBox, JTable, and
JTree.
360
pf3
pf4
pf5
pf8
pf9
pfa
pfd
pfe
pff
pf12
pf13
pf14
pf15
pf16
pf17
pf18
pf19
pf1a
pf1b
pf1c
pf1d
pf1e
pf1f
pf20
pf21
pf22
pf23
pf24
pf25
pf26
pf27
pf28
pf29
pf2a
pf2b
pf2c
pf2d
pf2e
pf2f
pf30
pf31
pf32
pf33
pf34
pf35
pf36
pf37
pf38
pf39
pf3a
pf3b
pf3c
pf3d
pf3e
pf3f
pf40
pf41
pf42
pf43
pf44
pf45
pf46
pf47
pf48
pf49
pf4a
pf4b
pf4c

Partial preview of the text

Download Java Programming Applets and JTree Components - Prof. Y. Daniel Liang and more Study Guides, Projects, Research Computer Science in PDF only on Docsity!

Advanced Swing Components

Objectives

  • Use JList to select single or multiple items in a list.
  • Use JComboBox to select a single item from a combo box.
  • Use JTable to display and process tables.
  • Use JTree to display data in a tree hierarchy.
  • Learn how to create custom renderers for JList, JComboBox, JTable, and JTree.
  • Learn how to create custom editors for JComboBox, JTable, and JTree.

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:

  • public JList(ListModel dataModel)
  • public JList(Object[] listData)
  • selectionBackground: The background color for selected cells.
  • selectionForeground: The foreground color for selected cells.
  • selectionMode: One of the three values (SINGLE_SELECTION, SINGLE_INTERVAL_SELECTION, MULTIPLE_INTERVAL_SELECTION) that indicate whether single items, single-interval items, or multiple-interval items can be selected.
  • selectionModel: An object that tracks list selection. List- selection models are rarely used explicitly. List-selection models are discussed in the section "List-Selection Models."
  • visibleRowCount: The preferred number of rows in the list that can be displayed without a scroll bar. The default value is 8.

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:

  1. Create a new project named listdemo.jpr and a new applet named TestList.java using the Applet wizard.
  2. In the UI designer of TestList.java, drop a JPanel to the north of the applet to create jpSelectionMode. Drop a JScrollPane

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.

  1. Set layout of jpSelectionMode to BorderLayout. Drop a JLabel and a JComboBox to jpSelectionMode, and rename the combo box to jcboSelectionMode.
  2. Create an array of strings named countries for the names of several countries. Add countries to the list using the following method:

jList1.setListData(countries);

  1. Add three items "SINGLE_SELECTION," SINGLE_INTERVAL_SELECTION," and "MULTIPLE_INTERVAL_SELECTION" to the combo box using the addItem() method.
  2. Generate the ActionEvent handler for the combo box, and implement it to set a selection mode for the list, as shown in Listing 8.1.
  3. Generate the ListSelectionEvent handler for the list, and implement it to display the selected items in the label, as shown in Listing 8.1.

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

  1. Switch to the UI designer and set the model property of jList to listModel.
  2. Generate the ActionEvent handlers for the combo box, the Add New Item button, and the Remove Selected Item button, and implement these handlers for setting a selection mode, adding a new element, and deleting elements in the list, as shown in Listing 8.2.
  3. Generate the ListSelectionEvent handler for the list and implement it to display the selected items in the label, as shown in Listing 8.2.

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:

  1. Reopen project listdemo.jpr and create a new applet named TestListCellRenderer.java using the Applet wizard.
  2. In the UI designer of TestListCellRenderer.java, drop a JSplitPanel to the center of the applet. Drop a JScrollPane to the left part of the split pane and a JList to the scroll pane to create jList1. Drop an ImageViewer to the right part of the split pane to create imageViewer1.
  3. Switch to the source pane to create images for the flags of several countries, as shown in Listing 8.5. Create an instance of MyListModel named listModel, and set the model property of jList to this instance. Create an instance of MyListCellRenderer, and set the cellRenderer property of jList1 to this instance.
  4. Generate the ListSelectionEvent handler (valueChanged for the list, and implement it to display the selected flag in imageViewer1.

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:

  • public JComboBox(ComboBoxModel model)
  • public JComboBox(Object[] objectArray)
  • public JComboBox(Vector vector)

The following properties of JComboBox are often useful:

  • actionCommand: An action command string associated with the JComboBox.
  • editable: A boolean value indicating whether the combo box can be edited. The default value is false.
  • itemCount: The number of items in the combo box. This property is read-only.
  • maximumRowCount: The maximum number of rows that can be seen without scrolling. The default value is 8.
  • model: An object that maintains the data for the list. Combo box models must be used explicitly to add or delete items in a combo box.
  • popupVisible: A boolean value indicating whether the popup menu that contains the list is displayed. The default value is false, which means that the user has to click the combo box to display the popup menu.
  • renderer: An instance of the class that implements the ListCellRenderer interface. The renderer is responsible for rendering the cell in the combo box.
  • selectedIndex: The index of the selected item in the combo box.
  • selectedItem: The current selected object in the combo box.

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