Date post: | 06-Jan-2018 |
Category: |
Documents |
Upload: | imogene-blake |
View: | 223 times |
Download: | 2 times |
1
Chapter 24 Advanced Swing Components
Prerequisites for Part VII
Chapter 21 JavaBeans, Bean Events, and MVC
Chapter 14 Applets, Images, and Audio
Chapter 22 Containers, Layout Managers, and Borders
Chapter 23 Menus, Toolbars, Dialogs, and Internal Frames
Chapter 24 Advanced Swing Components
2
Objectives· To understand the Swing model-view-controller
architecture (§24.2).· To use JSpinner to scroll the next and previous values
(§24.3).· To use JList to select single or multiple items in a list
(§24.4). · To use JComboBox to select or edit a single item from a
combo box (§24.5).· To use JTable to display and process tables (§24.6).· To use JTree to display data in a tree hierarchy (§24.7).· To create custom renderers for JSpinner, JList,
JComboBox, JTable, and JTree (§24.2 – 24.7).
3
Swing Model-View-Controller Architecture Each Swing user interface component (except some containers and dialog boxes such as JPanel, JSplitPane, JFileChooser, and JColorChooser) has a property named model that refers to its data model.
Generic Model Interface
Generic Swing Component Each Swing component contains the model property
Default Model Class Implements the model interface
javax.swing.ButtonModel +actionCommand: String +nemonic: String Other properties omitted . .
.
javax.swing.JButton +model: ButtonModel +actionCommand: String +nemonic: String Other properties
javax.swing.DefaultButtonModel
(A) Generic Swing model-view architecture (B) JButton model-view implementation
The data model is defined in an interface whose name ends with Model. For example, the model for button component is ButtonModel.
Most model interfaces have a default implementation class that is commonly named DefaultX, where X is its model interface name. For example, the default implementation class for ButtonModel is DefaultButtonModel.
4
Swing Components and Their ModelsFor convenience, most Swing components contain some properties of their models, and these properties can be accessed and modified directly from the component without knowing the existence of the model. For example, the properties actionCommand and mnemonic are defined in both ButtonModel and JButton. Actually, these properties are in the AbstractButton class. Since JButton is a subclass of AbstractButton, JButton inherits all the properties from AbstractButton.
It is unnecessary to use the models for the simple Swing components such as JButton, JToggleButton, JCheckBox, JRadioButton, JTextField, and JTextArea, because the frequently used properties in their models are also in these components. You can access and modify these properties directly through the components. For advanced components such as JSpinner, JList, JComboBox, JTable, and JTree, you have to work with their models to store, access and modify data.
5
JSpinner A spinner is a text field with a pair of tiny arrow buttons on its right side that enable the user to select numbers, dates, or values from an ordered sequence, as shown in Figure 24.2. The keyboard up/down arrow keys also cycle through the elements. The user may also be allowed to type a (legal) value directly into the spinner. A spinner is similar to a combo box, but a spinner is sometimes preferred because it doesn't require a drop down list that can obscure important data.
6
The JSpinner ClassA JSpinner's sequence value is defined by the SpinnerModel interface, which manages a potentially unbounded sequence of elements. The model doesn't support indexed random access to sequence elements. Only three sequence elements are accessible at a time: current, next and previous using the methods getValue(), getNextValue(), and getPreviousValue(), respectively.
javax.swing.JSpinner
-model: SpinnerModel -editor: JComponent
+JSpinner()
+JSpinner(model: SpinnerModel) +getNextValue(): Object +getPreviousValue(): Object +getValue(): Object +setValue(value: Object): void +addChangeListener(l: ChangeListener) : void +removeChangeListener(l: ChangeListener): void
javax.swing.SpinnerModel
Specifies a model with get/set methods. Specifies an editor with get/set methods. Constructs a JSpinner with a SpinnerNumberModel with initial value 0 and no minimum or maximum limits. Constructs a JSpinner with a specified SpinnerModel. Gets the next element value in this JSpinner. Gets the next element value in this JSpinner. Gets the current element value in this JSpinner. Sets the current element value. Adds a listener for value change. Removes a listener.
1 1
7
Example 24.1 A Simple JSpinner Demo
Problem: This example creates a JSpinner object for a sequence of numbers and displays the previous, current, and next number from the spinner on a label.
SimpleSpinner
Run
NOTE: If you create a JSpinner object without specifying a model, the spinner displays a sequence of integers.
8
Spinner ModelsSpinnerModel is an interface for all spinner models. AbstractSpinnerModel is a convenience abstract class that implements SpinnerModel and provides the implementation for the registration/deregistration methods. SpinnerListModel, SpinnerNumberModel, and SpinnerDateModel are concrete implementations of SpinnerModel.
javax.swing.SpinnerModel
+getPreviousValue(): Object +getNextValue(): Object +getValue(): Object +setValue(value: Object): void +addChangeListener(l: ChangeListener) : void +removeChangeListener(l: ChangeListener): void
AbstractSpinnerModel
SpinnerNumebrModel
SpinnerListModel SpinnerDateModel
Gets the previous element value. Gets the next element value. Gets the current element value. Sets the current element value. Adds a listener for value change. Removes a listener.
9
SpinnerListModelSpinnerListModel (see Figure 24.6) is a simple implementation of SpinnerModel whose values are stored in a java.util.List.
javax.swing.SpinnerListModel
-list: java.util.List
+SpinnerListModel() +SpinnerListModel(values: List) +SpinnerListModel(values: Object[]) +getList(): List +setList(list: List): void
Stores data in a list. Constructs a SpinnerListModel that contains “empty” string element. Constructs a SpinnerListModel with the specified list. Constructs a SpinnerListModel with the specified array. Gets the list where data is stored. Sets a new list for the model .
javax.swing.SpinnerModel
javax.swing.AbstractSpinnerModel
10
SpinnerNumberModel SpinnerNumberModel (see Figure 24.7) is a concrete implementation of SpinnerModel that represents a sequence of numbers. It contains the properties maximum, minimum, and stepSize.
javax.swing.SpinnerNumberModel
-maximum: java.lang.Comparable -minimum: java.lang.Comparable -stepSize: java.lang.Number -value: java.lang.Number
+SpinnerNumberModel()
+SpinnerNumberModel(value: int, minimum: int, maximum: int, stepSize: int)
+SpinnerNumberModel(value: double, minimum: double, maximum: double, stepSize: double)
+SpinnerNumberModel(value: Number, minimum: Comparable, maximum: Comparable, stepSize: Number)
Specifies the upper bound of the sequence with get/set methods. Specifies the lower bound of the sequence with get/set methods. Specifies the interval in the sequence with get/set methods. Holds the current selected value with get/set methods. Constructs an unbounded SpinnerNumberModel with an initial value
of zero and stepSize equal to one. Constructs a SpinnerNumberModel with the specified initial value,
minimum/maximum bounds, and stepSize in int. Constructs a SpinnerNumberModel with the specified initial value, minimum/maximum bounds, and stepSize in double. Constructs a SpinnerNumberModel that represents a closed sequence of numbers from minimum to maximum.
javax.swing.SpinnerModel
javax.swing.AbstractSpinnerModel
11
SpinnerDateModelSpinnerDateModel (see Figure 24.8) is a concrete implementation of SpinnerModel that represents a sequence of dates. The upper and lower bounds of the sequence are defined by properties called start and end and the size of the increase or decrease computed by the nextValue and previousValue methods is defined by a property called calendarField.
javax.swing.SpinnerDateModel
-start: java.lang.Comparable -end: java.lang.Comparable -calendarField: int -value: java.util.Calendar
+SpinnerDateModel()
+SpinnerDateModel(value: Date, start: Comparable, end: Comparable, calendarField: int)
Specifies the start date (upper bound) in the model with get/set methods. Specifies the end date (lower bound) in the model with get/set methods. Specifies the calendar field (interval) in the sequence with get/set methods. Holds the current selected date with get/set methods. Constructs an unbounded SpinnerDateModel whose initial value is the
current date, calendarField is equal to Calendar.DAY_OF_MONTH. Constructs a SpinnerNumberModel with the specified initial date, start/end
bounds, and calendarField.
javax.swing.SpinnerModel
javax.swing.AbstractSpinnerModel
12
Example 24.2 Using Spinner Models and Editors
Problem: This example uses a JSpinner component to display date and three separate JSpinner components to display day in a sequence of numbers, month in a sequence of strings, and year in a sequence of numbers, as shown in Figure 24.9. All these four components are synchronized. For example, if you change year in the spinner for year, the date value in the date spinner is updated accordingly.
SpinnerModelEditorDemo
Run
13
JList JList has two supporting models: a list model and a list-selection model. The list model is for storing and processing data. The list-selection model is for selecting items. By default, items are rendered as strings or icons. You can also create a custom renderer implementing the ListCellRenderer interface.
javax.swing.JList
-model: ListModel
-selectionMode: int
-selectionModel: ListSelectionModel
-cellRenderer: ListCellRenderer
ListModel
ListSelectionModel
ListCellRenderer r
AbstractListModel
DefaultListModel DefaultListCellRenderer
DefaultListSelectionModel
14
The JList Class
javax.swing.JList
-cellRenderer: ListCellRenderer -fixedCellHeight: int -fixedCellWidth: int -layoutOrientation: int -model: ListModel -selectedIndex: int -selectedIndices: int[] -selectedValue: Object -selectedValues: Object[] -selectedBackground: int -selectedForeground: int -selectionMode: int -selectionModel: ListSelectionModel -visibleRowCount: int
+JList() +JList(dataModel: ListModel) +JList(listData: Object[]) +JList(listData: Vector)
+setListData(listData: Object[]): void +setListData(listData: Vector): void
javax.swing.ListModel
The object that renders the list items. The fixed cell height value in pixels. The fixed cell width value. Defines the way list cells are laid out. Specifies the list model for this list. The index of the first selected item in this list. An array of all of the selected indices in increasing order. The first selected value. An array of the values for the selected values in increasing index order. The background color of the selected items. The foreground color of the selected items. Specifies whether single- or multiple-interval selections are allowed. Specifies a selection model. The preferred number of rows to display without using a scroll bar
(default: 8).
Constructs a default JList. Constructs a JList with the specified model. Constructs a JList with the data specified in the array. Constructs a JList with the data specified in the vector.
Sets an array of objects as data for the list. Sets a vector of objects as data for the list.
1 1
15
The layoutOrientation property
item1
item2
item3
item4
item5
(A) JList.VERTICAL
item1 item2 item3
item4 item5
(B) JList.HORIZONTAL_WRAP
item1 item3 item5
item2 item4
(C) JList.VERTICAL_WRAP
JList jlst = new JList();
jlst.setLayoutOrientation(int);
16
The selectionMode property JList jlst = new JList();
jlst.setSelectionMode(int);JList.SINGLE_SELECTION
JList.SINGLE_INTERVAL_SELECTION
JList.MULTIPLE_INTERVAL_SELECTION
17
Example 24.3 List Properties Demo
Problem: This example creates a list of a fixed number of items displayed as strings. The example enables you to dynamically set visibleRowCount from a spinner, layoutOrientation from a combo box, and selectionMode from a combo box, as shown in Figure 24.14. When you select one or more items, their values are displayed in a status label below the list.
ListPropertiesDemo Run
18
List Models
javax.swing.ListModel
+getElementAt(index: int): Object +getSize(): int +addListDataListener(l: ListDataListener): void +removeListDataListener(l: ListDataListener)
javax.swing.AbstractListModel
javax.swing.DefaultListModel +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
The JList class delegates the responsibilities of storing and maintaining data to its data model. The JList class itself does not have methods for adding or removing items from the list. These methods are supported in ListModel.
DefaultListModel extends AbstractListModel and implements the two methods getSize and getElementAt, which are not implemented by AbstractListModel.
AbstractListModel implements the registration methods in the ListModel, but does not implement the getSize and getElementAt methods.
19
Example 24.4 List Model Demo
Problem: This example creates a list using a list model and allows the user to add and delete items in the list, as shown in Figure 24.16. When the user clicks the Add new item button, an input dialog box is displayed to receive a new item.
ListModelDemo Run
20
List Cell RendererIn addition to delegating data storage and processing to list models, JList delegates the rendering of the list cells to list cell renderers.
JList
javax.swing.ListCellRenderer
+getListCellRendererComponent(list: JList, value: Object, index: int, isSelected: boolean, cellHasFocus: boolean): Component
DefaultListCellRenderer
YourCustomListCellRenderer
All list cell renderers implement the ListCellRenderer interface, which defines a single method, getListCellRendererComponent, as follows
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 a custom renderer by implementing ListCellRenderer.
21
Example 24.5 List Cell Renderer Demo
Problem: This example creates a list of countries and displays the country flags and country names in the list, as shown in Figure 24.18. When a country is selected in the list, its flag is displayed in a panel next to the list.
ListCellRendererDemo
Run
MyListCellRenderer
22
JComboBox
javax.swing.JComboBox
-actionCommand: String -editable: boolean -itemCount: int -maximumRowCount: int
-model: ComboBoxModel -popupVisible: boolean
-renderer: ListCellRenderer -selectedIndex: int -selectedItem: Object +JComboBox() +JComboBox(dataModel: ComboBoxModel) +JComboBox(items: Object[]) +getItemAt(index: int): void +addItem(anObject: Object): void +insertItemAt(anObject: Object, index: int): void +removeItemAt(index: int) : void +removeItem(anObject: Object): void +removeAllItems(): void
javax.swing.ComboBoxModel
An action string associated with the combo box. Specifies whether the cell can be edited. A read-only property to count the number of items. Specifies the maximum number of items the combo box can display
in the popup menu without a scrollbar. The data model that holds the items displayed by this combo box. Indicates whether the popup menu for displaying items is visible.
By default, it is false, which means the user has to click the combo box to display the popup menu.
The object that renders the list items in the combo box. Specifies the index of the selected item. Specifies the selected item. Constructs a default JComboBox. Constructs a JComboBox with the specified combo box model. Constructs a default JComboBox with an array of items. Gets the item at the specified index. Adds the item to the combo box. Inserts the item to the combo box at the specified index. Removes an item at the specified index from the combo box. Removes an item from the combo box. Removes all items from the combo box.
1 1
23
Combo Box Model
AbstractListModel
javax.swing.DefaultComboBoxModel +DefaultComboBoxModel() +DefaultComboBoxModel(items: Object[]) +DefaultComboBoxModel(vector: Vector) +addElement(element: Object): void +getElementAt(index: int): Object +getIndexOf(anObject: Object): int +getSelectedItem(): Object +getSize(): int +insertElementAt(obj: Object, index: int): void +removeAllElements(): void +removeElement(obj: Object): void +removeElementAt(index: int): void +setSelectedItem(obj: Object): void
ListModel
ComboModel
MutableComboModel
JComboBox 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 setSelectedItem methods for retrieving and setting a selected item.
The methods for adding and removing items are defined in the MutableComboBoxModel interface
DefaultComboBoxModel provides a concrete implementation for ComboModel.
24
Example 24.6 Combo Box Cell Renderer Demo
Problem: This example creates a combo box that contains a list of countries and displays the country flags and country names in the list cell. When a country is selected in the list, its flag is displayed in a panel below the combo box.
Run
ComboBoxCellRenderer
25
JTable JTable is a Swing component that displays data in rows and columns in a two-dimensional grid.
26
JTable and Its Supporting Models
NOTE: All the supporting interfaces and classes for JTable are grouped in the javax.swing.table package.
javax.swing.JTable
-model: TableModel
-columnModel: TableColumnModel
-selectionMode: int
-selectionModel: ListSelectionModel
-tableHeader: JTableHeader
TableModel
TableColumn
TableColumnModel
ListSelectionModel
JTableHeader
TableCellRenderer
TableCellEditor
AbstractTableModel
DefaultTableModel
27
The JTable Class
javax.swing.JTable
-autoCreateColumnsFromModel: boolean -autoResizeMode: int -cellEditor: TableCellEditor -cellSelectionEnabled: boolean -columnModel: TableColumnModel -columnSelectionAllowed: boolean -editingColumn: int -editingRow: int -gridColor: java.awt.Color -intercellSpacing: Dimension -model: TableModel -rowCount: int -rowHeight: int -rowMargin: int -rowSelectionAllowed: boolean -selectionBackground: java.awt.Color -selectionForeground: java.awt.Color -showGrid: boolean -selectionMode: int -selectionModel: ListSelectionModel -showHorizontalLines: boolean -showVerticalLines: boolean -tableHeader: JTableHeader
+JTable() +JTable(numRows: int, numColumns: int) +JTable(rowData: Object[][], columnData: Object[]) +JTable(dm: TableModel) +JTable(dm: TableModel, cm: TableColumnModel) +JTable(dm: TableModel, cm: TableColumnModel,
sm: ListSelectionModel) +JTable(rowData: Vector, columnNames: Vector) +addColumn(aColumn: TableColumn): void +clearSelection(): void +editCellAt(row: int, column: int): void +getDefaultEditor(column: Class): TableCellEditor +getDefaultRenderer(col: Class): TableCellRenderer +setDefaultEditor(column: Class, editor:
TableCellEditor): void +setDefaultRenderer(column: Class, editor:
TableCellRenderer): void
Indicates whether the columns are created in the table (default: true). Specifies how columns are resized (default: SUBSEQUENT_COLUMNS). Specifies a cell editor. Specifies whether individual cells can be selected (Obsolete since JDK 1.3). Maintains the table column data. Specifies whether the rows can be selected (default: false). Specifies the column of the cell that is currently being edited. Specifies the row of the cell that is currently being edited. The color used to draw grid lines ((default: GRAY). Specifies the horizontal and vertical margins between cells (default: 1, 1).
Maintains the table model. Read-only property that counts the number of rows in the table. Specifies the row height of the table (default: 16 pixels). Specifies the vertical margin between rows (default: 1 pixel). Specifies whether the rows can be selected (default: true). The background color of selected cells. The foreground color of selected cells. Specify whether the grid lines are displayed (write-only, default: true). Specifies a selection mode (write-only). Specifies a selection model. Specifies whether the horizontal grid lines are displayed (default: true). Specifies whether the vertical grid lines are displayed (default: true). Specifies a table header.
Creates a default JTable with all default models. Creates a JTable with the specified number of empty rows and columns. Creates a JTable with the specified row data and column header names. Creates a JTable with the specified table model. Creates a JTable with the specified table model and table column model. Creates a JTable with the specified table model, table column model,
and selection model. Creates a JTable with the specified row data and column data in vectors. Adds a new column to the table. Deselects all selected columns and rows. Edits the cell if it is editable. Returns the default editor for the column. Returns the default renderer for the column. Sets the default editor for the column. Sets the default renderer for the column.
28
Example 24.7 Table Properties Demo
Problem: This example demonstrates the use of several JTable properties. The example creates a table and allows the user to choose an Auto Resize Mode, specify the row height and margin, and indicate whether the grid is shown.
RunTablePropertiesDemo
29
Table Models javax.swing.table.TableModel
+getColumnClass(columnIndex: int): Class +getColumnName(columnIndex: int): String +getColumnCount(): int +getRowCount(): int +getValueAt(rowIndex: int, columnIndex: int):
Object +setValueAt(aValue: Object, rowIndex:
int, columnIndex: int): void +isCellEditable(rowIndex: int , columnIndex:
int): boolean +addTableModelListener(l:
TableModelListener): void +removeTableModelListener(l:
TableModelListener): void
javax.swing.table.AbstractTableModel
javax.swing.table.DefaultTableModel
+DefaultTableModel() +DefaultTableModel(rowCount: int, columnCount: int) +DefaultTableModel(columnNames: Object[], rowCount: int) +DefaultTableModel(data: Object[][], columnNames: Object[]) +DefaultTableModel(columnNames: Vector, rowCount: int) +DefaultTableModel(data: Vector, columnNames: Vector) +DefaultTableModel(rowData: Vector, columnNames: Vector) +addColumn(columnName: Object): void +addColumn(columnName: Object, Object[] columnData) +addColumn(columnName: Object, columnData: Vector) +addRow(rowData: Object[]): void +addRow(rowData: Vector): void +getColumnCount(): int +getDataVector(): Vector +getRowCount(): int +insertRow(row: int, rowData: Object[]): void +insertRow(row: int, rowData: Vector): void +setColumnCount(columnCount: int): void +setColumnIdentifiers(newIdentifiers: Object[]): void +setColumnIdentifiers(columnIdentifiers: Vector): void +setDataVector(dataVector: Object[][], columnIdentifiers:
Object[]): void +setDataVector(dataVector: Vector, columnIdentifiers: Vector):
void +setNumRows(rowCount: int): void +setRowCount(rowCount: int): void
JTable delegates data storing and processing to its table data model. A table data model must implement the TableModel interface, which defines the methods for registering table model listeners, manipulating cells, and obtaining row count, column count, column class, and column name.
The AbstractTableModel class provides partial implementations for most of the methods in TableModel. It takes care of the management of listeners and provides some conveniences for generating TableModelEvents and dispatching them to the listeners.
The DefaultTableModel provides concrete storage for data using a vector.
30
Table Column Model javax.swing.table.TableColumnModel
+addColumn(aColumn: TableColumn): void +getColumn(columnIndex: int): TableColumn +getColumnCount(): int +getColumnIndex(columnIdentifier:Object): int +getColumnMargin(): int +getColumns(): Enumeration +getColumnSelectionAllowed(): boolean +getSelectedColumnCount(): int +getSelectedColumns(): void +getSelectionModel(): ListSelectionModel +getTotalColumnWidth(): int +moveColumn(columnIndex: int, newIndex: int): void +removeColumn(column: TableColumn): void +setColumnMargin(newMargin: int): void +setColumnSelectionAllowed(flag: boolean): void +setSelectionModel(newModel: ListSelectionModel): void
javax.swing.tableDefaultTableColumnModel
javax.swing.table.TableColumn
Table column models manage columns in a table. They can be used to select, add, move, and remove table columns. A table column model must implement the TableColumnModel interface, which defines the methods for registering table column model listeners, and for accessing and manipulating columns.
DefaultTableColumnModel is a concrete class that implements TableColumnModel and stores its columns in a vector and contains an instance.
31
The TableColumn Class The column model deals with all the columns in a table. The TableColumn class is used to model an individual column in the table. An instance of TableColumn for a specified column can be obtained using the getColumn(index) method in TableColumnModel or the getColumn(columnIdentifier) method in JTable.
javax.swing.table.TableColumn +cellEditor: TableCellEditor +cellRenderer: TableCellRenderer +headerRenderer: TableCellRenderer +headerValue: Object +identifier: Object +maxWidth: int +minWidth: int +modelIndex: int +preferredWidth: int +resizable: boolean +width: int
+TableColumn() +TableColumn(modelIndex: int) +TableColumn(modelIndex: int, width: int) +TableColumn(modelIndex: int, width: int,
cellRenderer: TableCellRendere) +sizeWidthToFit(): void
The editor for editing a cell inf this column. The renderer for displaying a cell in this column. The renderer for displaying the header of this column. The header value of this column. The identifier for this column. The maximum width of this column. The minimum width of this column (default: 15 pixels). The index of the column in the table model (default: 0). The preferred width of this column (default: 75 pixels). Indicates whether this column can be resized (default: true). Specifies the width of this column (default: 75 pixels).
Constructs a default table column. Constructs a table column for the specified column. Constructs a table column with the specified column and width. Constructs a table column with the specified column, width, and
cell renderer. Resizes the column to fit the width of its header cell.
32
The JTableHeader ClassJTableHeader is a GUI component that manages the header of the JTable (see Figure 24.29). When you create a JTable, an instance of JTableHeader is automatically created and stored in the tableHeader property.
javax.swing.table.JTableHeader +columnModel: TableColumnModel +draggedColumn: TableColumn +draggedDistance: TableCellRenderer +reorderingAllowed: boolean +resizingAllowed: boolean +resizingColumn: TableColumn +table: JTable
+JTableHeader() +JTableHeader(TableColumnModel cm)
The TableColumnModel of the table header. The column being dragged. The distance from its original position to the dragged position. Whether reordering of columns is allowed (default: true). Whether resizing of columns is allowed (default: true). The column being resized. The table for which this object is the header.
Constructs a JTableHeader with a default TableColumnModel. Constructs a JTableHeader with with a TableColumnModel.
33
Example 24.8 Modifying Rows and Columns
Problem: This example demonstrates the use of table models, table column models, list-selection models, and the TableColumn class. The program allows the user to choose selection mode and selection type, to add or remove rows and columns, and to save, clear, and restore table.
RunTableModelDemo
34
Table Renderers and Editors Table cells are painted by cell renderers. By default, a cell object's string representation (toString()) is displayed and the string can be edited as it was in a text field. JTable maintains a set of predefined renderers and editors, listed in Table 24.1, which can be specified to replace default string renderers and editors.
The predefined renderers and editors are automatically located and loaded to match the class returned from the getColumnClass() method in the table model. To use a predefined renderer or editor for a class other than String, you need to create your own table model by extending a subclass of TableModel. In your table model class, you need to override the getColumnClass() method to return the class of the column, as follows:
public Class getColumnClass(int column) {
return getValueAt(0, column).getClass();
}
By default, all cells are editable. To prohibit a cell from being edited, override the isCellEditable(int rowIndex, int columnIndx) method in TableModel to return false. By default, this method returns true in AbstractTableModel.
35
Example 24.9 Using Predefined Table Renderers and Editors
Problem: Write a program that displays a table for the books. The table consists of three rows with column names Title, Copies Needed, Publisher, Date Published, In-Stock, and Book Photo, as shown in Figure 24.32. Display all the columns using the predefined renderers and editors. Assume dates and icons are not editable; prohibit users from editing of these two columns.
RunMyTableModel TableCellRendererEditorDemo
36
Custom Table Renderers and Editors Predefined renderers and editors are convenient and easy to use, but their functions are limited. The predefined image icon renderer displays the image icon in a label. The image icon cannot be scaled. If you want the whole image to fit in a cell, you need to create a custom renderer.
A custom renderer can be created by extending the DefaultTableCellRenderer, which is a default implementation for the TableCellRender interface. The custom renderer must override the getTableCellRendererComponent() to return a component for rendering the table cell. The getTableCellRendererComponent() is defined as follows:
public Component getTableCellRendererComponent
(JTable table, Object value, boolean isSelected,
boolean isFocused, int row, int column)
This method signature is very similar to the getListCellRendererComponent() method used to create custom list cell renderers.
37
Example 24.10 Using Custom Table Renderers and Editors
Problem: Revise Example 24.9, “Using Predefined Table Renderers and Editors,” to display scaled image icons and to use a custom combo editor to edit the cells in the Publisher column.
RunCustomTableCellRenderEditorDemo
38
Table EventsJTable does not fire table events. It fires the events such as MouseEvent, KeyEvent, and ComponentEvent inherited from its superclass JComponent. Table events are fired by table models, table column models, and table-selection models whenever changes are made to these models. Table models fire TableModelEvent when table data are changed. Table column models fire TableColumnModelEvent when columns are added, removed, or moved, or when the column selection changes. Table-selection models fire ListSelectionEvent when the selection changes.
39
Example 24.11 Using Table Events Problem: This example demonstrates handling table events. The program displays messages on a text area when a row or a column is selected, when a cell is edited, or when a column is removed.
RunTableEventDemo
40
JTreeJTree is a Swing component that displays data in a treelike hierarchy.
RootLeaf
41
Tree ModelsWhile JTree displays the tree, the data representation of the tree is handled by TreeModel, TreeNode, and TreePath. TreeModel represents the entire tree, TreeNode represents a node, and TreePath represents a path to a node. Unlike the ListModel or TableModel, the tree model does not directly store or manage tree data. Tree data are stored and managed in TreeNode and TreePath.
javax.swing.JTree
-model: TreeModel
-anchorPath: TreePath
-leadPath: TreePath
-selectionModel: TreeSelectionModel
-cellEditor: TreeCellEditor
-cellRenderer: TreeCellEditor
TreeModel TreeSelectionModel
TreeCellRenderer
TreeNode
TreeCellEditor
DefaultTreeModel
MutableTreeNode
TreePath
DefaultMutableTreeNode
DefaultTreeCellRenderer
DefaultTreeCellEditor
DefaultTreeSelectionModel
The TreeSelectionModel interface handles tree node selection.
The DefaultTreeCellEditor can be used to edit the cells in a text field.
The DefaultTreeCellRenderer class provides a default tree node renderer that can display a label and/or an icon in a node.
42
The JTree Class
javax.swing.JTree
#cellEditor: TreeCellEditor #cellRenderer: TreeCellRenderer #editable: boolean #model: TreeModel #rootVisible: boolean #rowHeight: int
#scrollsOnExpand: boolean
#selectionModel: TreeSelectionModel #showsRootHandles: boolean #toggleClickCount: int -anchorSelectionPath: TreePath -expandsSelectedPaths: boolean -leadSelectionPaths: TreePath
+JTree() +JTree(value: java.util.Hashtable)
+JTree(value: Object[])
+JTree(newModel: TreeModel) +JTree(root: TreeNode) +JTree(root: TreeNode, asksAllowsChildren:
boolean) +JTree(value: Vector)
+addSelectionPath(path: TreePath): void +addSelectionPaths(paths: TreePath[]): void +addSelectionRow(row: int): void +addSelectionRows(rows: int[]): void +clearSelection() : void +collapsePath(path: TreePath): void +getSelectionPath(): TreePath +getSelectionPaths(): TreePath[] +getLastSelectedPathComponent() +getRowCount():int +removeSelectionPath(path: TreePath): void +removeSelectionPaths(paths: TreePath[]):void
Specifies a cell editor used to edit entries in the tree. Specifies whether individual cells can be selected (Obsolete since JDK 1.3). Specifies whether the cells are editable (default: false). Maintains the tree model. Specifies whether the root is displayed (depending on the constructor). Specifies the height of the row for the node displayed in the tree (default: 16 pixels).
If true, when a node is expanded, as many of the descendants are scrolled to be visible (default: 16 pixels).
Models the set of selected nodes in this tree. Specifies whether the root handles are displayed (default: true). Number of mouse clicks before a node is expanded (default: 2). The path identified as the anchor. True if paths in the selection should be expanded (default: true). The path identified as the lead. Creates a JTree with a sample tree model, as shown in Figure 24.35. Creates a JTree with an invisible root and the keys in the Hashtable
key/value pairs as its children. Creates a JTree with an invisible root and the elements in the array as
its children. Creates a JTree with the specified tree model. Creates a JTree with the specified tree node as its root. Creates a JTree with the specified tree node as its root and decides
whether a node is a leaf node in the specified manner. Creates a JTree with an invisible root and the elements in the vector as
its children. Adds the specified TreePath to the current selection. Adds the specified TreePaths to the current selection. Adds the path at the specified row to the current selection. Adds the path at the specified rows to the current selection. Clears the selection. Ensures that the node identified by the specified path is collapsed and
viewable. Returns the path from the root to the first selected node. Returns the paths from the root to all the selected nodes. Returns the last node in the first selected TreePath. Returns the number of rows currently being displayed. Removes the node in the specified path. Removes the node in the specified paths.
43
Example 24.12 Simple Tree DemoProblem: Write a program to create four trees: a default tree using the no-arg constructor, a tree created from an array of objects, a tree created from a vector, and a tree created from a hash table, as shown in Figure 24.38. Enable the user to dynamically set the properties for rootVisible, rowHeight, and showsRootHandles.
RunSimpleTreeDemo
44
TreeModel and DefaultTreeModel TreeModel contains the structural information about the tree, and tree data are stored and managed by TreeNode.
javax.swing.tree.TreeModel +getChild(parent: Object, index: int): Object +getChildCount(parent: Object): int +getIndexOfChild(parent: Object, child: Object): int +getRoot(): Object +isLeaf(node: Object): boolean +addTreeModelListener(listener:
TreeModelListener): void +removeTreeModelListener(listener:
TreeModelListener): void +valueForPathChanged(path: TreePath, newValue:
Object): void
javax.swing.tree.DefaultTreeModel
#asksAllowsChildren: Boolean
#root: TreeNode +DefaultTreeModel(root: TreeNode) +DefaultTreeModel(root: TreeNode,
asksAllowsChildren: boolean) +asksAllowsChildren(): boolean +getPathToRoot(aNode: TreeNode): TreeNode[] +insertNodeInto(newChild: MutableTreeNode,
parent: MutableTreeNode, index: int): void +reload(): void +removeNodeFromParent(node: MutableTreeNode):
void
Returns the child of parent at the index in the parent's child array. Returns the number of children of the specified parent in the tree model. Returns the index of child in parent. If parent or child is null, returns –1. Returns the root of the tree. Returns null if the tree is empty. Returns true if the specified node is a leaf. Adds a listener for the TreeModelEvent posted after the tree changes. Removes a listener previously added with addTreeModelListener.
Messaged when the user has altered the value for the item identified by path to newValue.
Tells how leaf nodes are determined. True if only nodes that do not allow children are leaf nodes, false if nodes that have no children are leaf nodes.
The root of the tree. Creates a DefaultTreeModel with the specified root. Creates a DefaultTreeModel with the specified root and decides whether a
node is a leaf node in the specified manner. Returns asksAllowsChildren. Returns the nodes in an array from root to the specified node. Inserts newChild at location index in parents children. Reloads the model (invoke this method if the tree has been modified) Removes the node from its parent.
DefaultTreeModel is a concrete implementation for TreeModel that uses TreeNodes.
45
TreeNode, MutableTreeNode, and
DefaultMutableTreeNode
TreeNode stores models a single node in the tree.
javax.swing.tree.TreeNode +children(): java.util.Enumeration +getAllowsChildren(): boolean +getChildAt(childIndex: int): TreeNode +getChildCount(): int +getIndex(node: TreeNode): int +getParent(): TreeNode +isLeaf():boolean
javax.swing.tree.MutableTreeNode
+insert(child: MutableTreeNode, index: int): void +remove(index: int): void +remove(node: MutableTreeNode): void +removeFromParent(): void +setParent(newParent: MutableTreeNode): void +setUserObject(object: Object): void
Returns the children of this node. Returns true if this node can have children. Returns the child TreeNode at index childIndex. Returns the number of children under this node. Returns the index of the specified node in the current node’s children. Returns the parent of this node. Returns true if this node is a leaf.
Adds the specified child under this node at the specified index. Removes the child at the specified index from this node’s child list. Removes the specified node from this node’s child list. Removes this node from its parent. Sets the parent of this node to the specified newParent. Resets the user object of this node to the specified object.
javax.swing.tree.DefaultMutableTreeNode
#allowsChildren: Boolean #parent: MutableTreeNode #userObject: Object +DefaultMutableTreeNode() +DefaultMutableTreeNode(userObject: Object) +DefaultMutableTreeNode(userObject: Object,
allowsChildren: boolean) +add(MutableTreeNode newChild) +getChildAfter(aChild: TreeNode): TreeNode +getChildBefore(aChild: TreeNode): TreeNode +getFirstChild(): TreeNode +getLastChild(): TreeNode +getFirstLeaf(): DefaultMutableTreeNode +getLastLeaf(): DefaultMutableTreeNode +getNextLeaf(): DefaultMutableTreeNode +getPreviousLeaf(): DefaultMutableTreeNode +getLeafCount(): int +getDepth(): int +getLevel(): int +getNextNode(): DefaultMutableTreeNode +getPreviousNode(): DefaultMutableTreeNode +getSiblingCount(): int +getNextSibling(): DefaultMutableTreeNode +getPath(): TreeNode[] +getRoot(): TreeNode +isRoot(): boolean +breadthFirstEnumeration(): Enumeration +depthFirstEnumeration(): Enumeration +postorderEnumeration(): Enumeration +preorderEnumeration(): Enumeration
True if the node is able to have children. Stores the parent of this node. Stores the content of this node.
Creates a tree node without user object, and allows children. Creates a tree node with the specified user object, and allows children. Creates a tree node with the specified user object and the specified mode to
indicate whether children are allowed.
Adds the specified node to the end of this node's child vector. Returns the next (previous) sibling of the specified child in this node's child
vector.
These two methods return this node's first (last) child in the child’s vector of this node.
These four methods return the first (last, next, and previous) leaf that is a descendant of this node. The first (last, next, and previous) leaf is recursively defined as the first (last, next, and previous) child’s first (last, next, and previous) leaf.
Returns the total number of leaves that are descendants of this node. Returns the depth of the tree rooted at this node. Returns the distance from the root to this node. Returns the node that follows (precedes) this node in a preorder traversal of this node. Returns the number of siblings of this node. Returns the next sibling of this node in the parent's child vector. Returns the path from the root to this node. Returns the root of the tree that contains this node. Returns true if this node is the root of the tree. Creates and returns an enumeration that traverses the subtree rooted at this
node in breadth-first order (depth-first order, postorder, preorder). These traversals were discussed in Chapter 17, “Data Structure Implementations.”
MutableTreeNode defines a subinterface of TreeNode with additional methods for changing the content of the node, for inserting and removing a child node, for setting a new parent, and for removing the node itself.
DefaultMutableTreeNode is a concrete implementation of MutableTreeNode.
46
Example 24.13 Tree Model DemoProblem: Write a program to create two trees that displays world, continents, countries and states. The two trees display identical contents. The program also displays the properties of the tree in a text area.
RunTreeModelDemo
47
The TreePath Class The TreePath class represents a path from an ancestor to a descendant in a tree.
javax.swing.tree.TreePath +TreePath(singlePath: Object) +TreePath(path: Object[]) +getLastPathComponent(): Object +getParentPath(): TreePath +getPath(): Object[] +getPathComponent(element: int): Object +getPathCount(): int +isDescendant(aTreePath: TreePath): Boolean +pathByAddingChild(child: Object): TreePath
Constructs a TreePath containing only a single element. Constructs a path from an array of objects. Returns the last component of this path. Returns a path containing all but the last path component. Returns an ordered array of objects containing the components of this TreePath. Returns the path component at the specified index. Returns the number of elements in the path. Returns true if aTreePath contains all the components in this TreePath. Returns a new path containing all the elements of this TreePath plus child.
48
TreeSelectionModel and DefaultTreeSelectionModel
The selection of tree nodes is defined in the TreeSelectionModel interface.
javax.swing.tree.TreeSelectionModel
+addSelectionPath(path: TreePath): void +addSelectionPaths(paths: TreePath[]): void +clearSelection() : void +getLeadSelectionPath(): TreePath +getSelectionCount(): int +getSelectionPath(): TreePath +getSelectionPaths(): TreePath[] +getSelectionMode(): int +removeSelectionPath(path: TreePath): void +removeSelectionPaths(paths: TreePath[]):void +setSelectionMode(mode: int): void +setSelectionPath(path: TreePath): void +setSelectionPaths(paths: TreePath[]): void +addTreeSelectionListener(x: TreeSelectionListener): void +removeTreeSelectionListener(x: TreeSelectionListener): void
Adds the specified TreePath to the current selection. Adds the specified TreePaths to the current selection. Clears the selection. Returns the last path in the selection. Returns the number of paths in the selection. Returns the first path in the selection. Returns all the paths in the selection. Returns the current selection mode, Removes path from the selection. Removes paths from the selection. Sets the selection mode. Sets the selection to path. Sets the selection to paths. Register a TreeSelectionListener. Remove a TreeSelectionListener.
javax.swing.tree.DefaultTreeSelectionModel
The DefaultTreeSelectionModel class is a concrete implementation of the TreeSelectionModel, which maintains an array of TreePath objects representing the current selection.
49
Example 24.14 Modifying Trees Problem: Write a program to create two trees that displays the same contents: world, continents, countries and states, as shown in Figure 24.44. For the left tree on the left, enable the user to choose a selection mode, add a new child under the first selected node, and remove all the selected nodes.
RunProcessTree
50
Tree Node Rendering DefaultTreeCellRenderer renderer = (DefaultTreeCellRenderer)jTree1.getCellRenderer(); renderer.setLeafIcon(yourCustomLeafImageIcon); renderer.setOpenIcon(yourCustomOpenImageIcon); renderer.setClosedIcon(yourCustomClosedImageIcon); renderer.setBackgroundSelectionColor(Color.red);
51
Tree Editing // Customize editor JComboBox jcboColor = new JComboBox(); jcboColor.addItem("red"); jcboColor.addItem("green"); jcboColor.addItem("blue"); jcboColor.addItem("yellow"); jcboColor.addItem("orange"); jTree1.setCellEditor(new DefaultCellEditor(jcboColor)); jTree1.setEditable(true);
52
Tree Rendering and Editing jTree1.setCellEditor (new DefaultTreeCellEditor(jTree1, new DefaultTreeCellRenderer(), new DefaultCellEditor(jcboColor)));
53
Tree Events JTree can fire TreeSelectionEvent and TreeExpansionEvent, among many other events. Whenever a new node is selected, JTree fires a TreeSelectionEvent. Whenever a node is expanded or collapsed, JTree fires a TreeExpansionEvent. To handle the tree selection event, a listener must implement the TreeSelectionListener interface, which contains a single handler named valueChanged method. TreeExpansionListener contains two handlers named treeCollapsed and treeExpanded for handling node expansion or node closing.