8 Advanced Swing Components Objectives • Use JList to select ...

48 downloads 165 Views 1MB Size Report
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.
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

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.1 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) 361

• public JList(Vector listData) If you have a list of a fixed number of string items, you can simply create it as follows: String[] listData = {"Item 1", "Item 2", "Item 3"}; JList jlst = new JList(listData);

JList supports three selection modes: single selection, singleinterval selection, and multiple-interval selection. Single selection allows only one item to be selected. Single-interval selection allows multiple selections, but the selected items must be contiguous. Multiple-interval selection is the most flexible, because it allows selections of any items at a given time. JList has the following useful properties: • cellRenderer: An object used to render the cells in a list. By default, an instance of DefaultListCellRenderer is used to display items in a list that can display strings or icons. Using custom cell renderer is introduced in the section, "List Cell Renderers." • listData: A write-only property used to set an array or a vector of objects for the list. • fixedCellHeight: The height of a list cell. All the cells in a list have the same height. If this property is not specified, the tallest item in the list dictates the cell height for all the cells. • fixedCellWidth: The width of a list cell. All the cells in a list have the same width. If this property is not specified, the widest item in the list dictates the cell width for all the cells. • model: An object that maintains the data for the list. List models must be used explicitly when adding or deleting items in a list. List models are introduced in the section "List Models." • prototypeCellValue: An object whose cell size dictates the cell size of the list. • selectedIndex: An int value indicating the index of the selected item in the list. • selectedIndices: An array of int values representing the indices of the selected items in the list. • selectedValue: The first selected value in the list. • selectedValues: An array of objects representing selected values in the list. This property is read-only. 362

• 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. Listselection 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.2 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 363

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. 3. Set layout of jpSelectionMode to BorderLayout. Drop a JLabel and a JComboBox to jpSelectionMode, and rename the combo box to jcboSelectionMode. 4. 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); 5. Add three items "SINGLE_SELECTION," SINGLE_INTERVAL_SELECTION," and "MULTIPLE_INTERVAL_SELECTION" to the combo box using the addItem() method. 6. 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. 7. 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 {

364

jbInit(); } catch(Exception e) { e.printStackTrace(); } } /**Component initialization*/ private void jbInit() throws Exception { this.setSize(new Dimension(400, 300)); jList1.setListData(countries); jList1.addListSelectionListener( new javax.swing.event.ListSelectionListener() { public void valueChanged(ListSelectionEvent e) { jList1_valueChanged(e); } }); jpSelectionMode.setLayout(borderLayout1); jcboSelectionMode.addActionListener( new java.awt.event.ActionListener() { public void actionPerformed(ActionEvent e) { jcboSelectionMode_actionPerformed(e); } }); jlblStatus.setText("Status"); jLabel1.setText("Choose Selection Mode"); this.getContentPane().add(jScrollPane1, BorderLayout.CENTER); jScrollPane1.getViewport().add(jList1, null); this.getContentPane().add(jpSelectionMode, BorderLayout.NORTH); jpSelectionMode.add(jLabel1, BorderLayout.WEST); jpSelectionMode.add(jcboSelectionMode, BorderLayout.CENTER); this.getContentPane().add(jlblStatus, BorderLayout.SOUTH); // Add selection modes to the combo box jcboSelectionMode.addItem("SINGLE_SELECTION"); jcboSelectionMode.addItem("SINGLE_INTERVAL_SELECTION"); jcboSelectionMode.addItem("MULTIPLE_INTERVAL_SELECTION"); } /**Handle item selection from a combo box*/ void jcboSelectionMode_actionPerformed(ActionEvent e) { String selectedMode = (String)jcboSelectionMode.getSelectedItem(); if (selectedMode.equals("SINGLE_SELECTION")) jList1.setSelectionMode(ListSelectionModel.SINGLE_SELECTION); else if (selectedMode.equals("SINGLE_INTERVAL_SELECTION")) jList1.setSelectionMode( ListSelectionModel.SINGLE_INTERVAL_SELECTION); if (selectedMode.equals("MULTIPLE_INTERVAL_SELECTION")) jList1.setSelectionMode( ListSelectionModel.MULTIPLE_INTERVAL_SELECTION); }

365

/**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