Presentation is loading. Please wait.

Presentation is loading. Please wait.

Liang, Introduction to Java Programming, Fifth Edition, (c) 2005 Pearson Education, Inc. All rights reserved. 0-13-148952-6 1 Chapter 24 Advanced Swing.

Similar presentations


Presentation on theme: "Liang, Introduction to Java Programming, Fifth Edition, (c) 2005 Pearson Education, Inc. All rights reserved. 0-13-148952-6 1 Chapter 24 Advanced Swing."— Presentation transcript:

1 Liang, Introduction to Java Programming, Fifth Edition, (c) 2005 Pearson Education, Inc. All rights reserved. 0-13-148952-6 1 Chapter 24 Advanced Swing Components

2 Liang, Introduction to Java Programming, Fifth Edition, (c) 2005 Pearson Education, Inc. All rights reserved. 0-13-148952-6 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 Liang, Introduction to Java Programming, Fifth Edition, (c) 2005 Pearson Education, Inc. All rights reserved. 0-13-148952-6 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. 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 Liang, Introduction to Java Programming, Fifth Edition, (c) 2005 Pearson Education, Inc. All rights reserved. 0-13-148952-6 4 Swing Components and Their Models For 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 Liang, Introduction to Java Programming, Fifth Edition, (c) 2005 Pearson Education, Inc. All rights reserved. 0-13-148952-6 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 Liang, Introduction to Java Programming, Fifth Edition, (c) 2005 Pearson Education, Inc. All rights reserved. 0-13-148952-6 6 The JSpinner Class A 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.

7 Liang, Introduction to Java Programming, Fifth Edition, (c) 2005 Pearson Education, Inc. All rights reserved. 0-13-148952-6 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 Liang, Introduction to Java Programming, Fifth Edition, (c) 2005 Pearson Education, Inc. All rights reserved. 0-13-148952-6 8 Spinner Models SpinnerModel 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.

9 Liang, Introduction to Java Programming, Fifth Edition, (c) 2005 Pearson Education, Inc. All rights reserved. 0-13-148952-6 9 SpinnerListModel SpinnerListModel (see Figure 24.6) is a simple implementation of SpinnerModel whose values are stored in a java.util.List.

10 Liang, Introduction to Java Programming, Fifth Edition, (c) 2005 Pearson Education, Inc. All rights reserved. 0-13-148952-6 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.

11 Liang, Introduction to Java Programming, Fifth Edition, (c) 2005 Pearson Education, Inc. All rights reserved. 0-13-148952-6 11 SpinnerDateModel SpinnerDateModel (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.

12 Liang, Introduction to Java Programming, Fifth Edition, (c) 2005 Pearson Education, Inc. All rights reserved. 0-13-148952-6 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 Liang, Introduction to Java Programming, Fifth Edition, (c) 2005 Pearson Education, Inc. All rights reserved. 0-13-148952-6 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.

14 Liang, Introduction to Java Programming, Fifth Edition, (c) 2005 Pearson Education, Inc. All rights reserved. 0-13-148952-6 14 The JList Class

15 Liang, Introduction to Java Programming, Fifth Edition, (c) 2005 Pearson Education, Inc. All rights reserved. 0-13-148952-6 15 The layoutOrientation property JList jlst = new JList(); jlst.setLayoutOrientation(int);

16 Liang, Introduction to Java Programming, Fifth Edition, (c) 2005 Pearson Education, Inc. All rights reserved. 0-13-148952-6 16 The selectionMode property JList jlst = new JList(); jlst.setSelectionMode(int); JList.SINGLE_SELECTION JList.SINGLE_INTERVAL_SELECTION JList.MULTIPLE_INTERVAL_SELECTION

17 Liang, Introduction to Java Programming, Fifth Edition, (c) 2005 Pearson Education, Inc. All rights reserved. 0-13-148952-6 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 Liang, Introduction to Java Programming, Fifth Edition, (c) 2005 Pearson Education, Inc. All rights reserved. 0-13-148952-6 18 List Models 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 Liang, Introduction to Java Programming, Fifth Edition, (c) 2005 Pearson Education, Inc. All rights reserved. 0-13-148952-6 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 Liang, Introduction to Java Programming, Fifth Edition, (c) 2005 Pearson Education, Inc. All rights reserved. 0-13-148952-6 20 List Cell Renderer 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 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 Liang, Introduction to Java Programming, Fifth Edition, (c) 2005 Pearson Education, Inc. All rights reserved. 0-13-148952-6 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 Liang, Introduction to Java Programming, Fifth Edition, (c) 2005 Pearson Education, Inc. All rights reserved. 0-13-148952-6 22 JComboBox

23 Liang, Introduction to Java Programming, Fifth Edition, (c) 2005 Pearson Education, Inc. All rights reserved. 0-13-148952-6 23 Combo Box Model 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 Liang, Introduction to Java Programming, Fifth Edition, (c) 2005 Pearson Education, Inc. All rights reserved. 0-13-148952-6 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 Liang, Introduction to Java Programming, Fifth Edition, (c) 2005 Pearson Education, Inc. All rights reserved. 0-13-148952-6 25 JTable JTable is a Swing component that displays data in rows and columns in a two-dimensional grid.

26 Liang, Introduction to Java Programming, Fifth Edition, (c) 2005 Pearson Education, Inc. All rights reserved. 0-13-148952-6 26 JTable and Its Supporting Models NOTE: All the supporting interfaces and classes for JTable are grouped in the javax.swing.table package.

27 Liang, Introduction to Java Programming, Fifth Edition, (c) 2005 Pearson Education, Inc. All rights reserved. 0-13-148952-6 27 The JTable Class

28 Liang, Introduction to Java Programming, Fifth Edition, (c) 2005 Pearson Education, Inc. All rights reserved. 0-13-148952-6 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. Run TablePropertiesDemo

29 Liang, Introduction to Java Programming, Fifth Edition, (c) 2005 Pearson Education, Inc. All rights reserved. 0-13-148952-6 29 Table Models 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 Liang, Introduction to Java Programming, Fifth Edition, (c) 2005 Pearson Education, Inc. All rights reserved. 0-13-148952-6 30 Table Column Model 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. DefaultTableColum nModel is a concrete class that implements TableColumnModel and stores its columns in a vector and contains an instance.

31 Liang, Introduction to Java Programming, Fifth Edition, (c) 2005 Pearson Education, Inc. All rights reserved. 0-13-148952-6 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.

32 Liang, Introduction to Java Programming, Fifth Edition, (c) 2005 Pearson Education, Inc. All rights reserved. 0-13-148952-6 32 The JTableHeader Class JTableHeader 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.

33 Liang, Introduction to Java Programming, Fifth Edition, (c) 2005 Pearson Education, Inc. All rights reserved. 0-13-148952-6 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. Run TableModelDemo

34 Liang, Introduction to Java Programming, Fifth Edition, (c) 2005 Pearson Education, Inc. All rights reserved. 0-13-148952-6 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 Liang, Introduction to Java Programming, Fifth Edition, (c) 2005 Pearson Education, Inc. All rights reserved. 0-13-148952-6 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. Run MyTableModel TableCellRendererEditorDemo

36 Liang, Introduction to Java Programming, Fifth Edition, (c) 2005 Pearson Education, Inc. All rights reserved. 0-13-148952-6 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 Liang, Introduction to Java Programming, Fifth Edition, (c) 2005 Pearson Education, Inc. All rights reserved. 0-13-148952-6 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. Run CustomTableCellRenderEditorDemo

38 Liang, Introduction to Java Programming, Fifth Edition, (c) 2005 Pearson Education, Inc. All rights reserved. 0-13-148952-6 38 Table Events JTable 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 Liang, Introduction to Java Programming, Fifth Edition, (c) 2005 Pearson Education, Inc. All rights reserved. 0-13-148952-6 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. Run TableEventDemo

40 Liang, Introduction to Java Programming, Fifth Edition, (c) 2005 Pearson Education, Inc. All rights reserved. 0-13-148952-6 40 JTree JTree is a Swing component that displays data in a treelike hierarchy. Root Leaf

41 Liang, Introduction to Java Programming, Fifth Edition, (c) 2005 Pearson Education, Inc. All rights reserved. 0-13-148952-6 41 Tree Models While 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. 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 Liang, Introduction to Java Programming, Fifth Edition, (c) 2005 Pearson Education, Inc. All rights reserved. 0-13-148952-6 42 The JTree Class

43 Liang, Introduction to Java Programming, Fifth Edition, (c) 2005 Pearson Education, Inc. All rights reserved. 0-13-148952-6 43 Example 24.12 Simple Tree Demo Problem: 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. Run SimpleTreeDemo

44 Liang, Introduction to Java Programming, Fifth Edition, (c) 2005 Pearson Education, Inc. All rights reserved. 0-13-148952-6 44 TreeModel and DefaultTreeModel TreeModel contains the structural information about the tree, and tree data are stored and managed by TreeNode. DefaultTreeModel is a concrete implementation for TreeModel that uses TreeNodes.

45 Liang, Introduction to Java Programming, Fifth Edition, (c) 2005 Pearson Education, Inc. All rights reserved. 0-13-148952-6 45 TreeNode, MutableTreeNode, and DefaultMutableTreeNode TreeNode stores models a single node in the tree. 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 Liang, Introduction to Java Programming, Fifth Edition, (c) 2005 Pearson Education, Inc. All rights reserved. 0-13-148952-6 46 Example 24.13 Tree Model Demo Problem: 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. Run TreeModelDemo

47 Liang, Introduction to Java Programming, Fifth Edition, (c) 2005 Pearson Education, Inc. All rights reserved. 0-13-148952-6 47 The TreePath Class The TreePath class represents a path from an ancestor to a descendant in a tree.

48 Liang, Introduction to Java Programming, Fifth Edition, (c) 2005 Pearson Education, Inc. All rights reserved. 0-13-148952-6 48 TreeSelectionModel and DefaultTreeSelectionModel The selection of tree nodes is defined in the TreeSelectionModel interface. The DefaultTreeSelectionM odel class is a concrete implementation of the TreeSelectionModel, which maintains an array of TreePath objects representing the current selection.

49 Liang, Introduction to Java Programming, Fifth Edition, (c) 2005 Pearson Education, Inc. All rights reserved. 0-13-148952-6 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. Run ProcessTree

50 Liang, Introduction to Java Programming, Fifth Edition, (c) 2005 Pearson Education, Inc. All rights reserved. 0-13-148952-6 50 Tree Node Rendering DefaultTreeCellRenderer renderer = (DefaultTreeCellRenderer)jTree1.getCellRenderer(); renderer.setLeafIcon(yourCustomLeafImageIcon); renderer.setOpenIcon(yourCustomOpenImageIcon); renderer.setClosedIcon(yourCustomClosedImageIc on); renderer.setBackgroundSelectionColor(Color.red);

51 Liang, Introduction to Java Programming, Fifth Edition, (c) 2005 Pearson Education, Inc. All rights reserved. 0-13-148952-6 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 Liang, Introduction to Java Programming, Fifth Edition, (c) 2005 Pearson Education, Inc. All rights reserved. 0-13-148952-6 52 Tree Rendering and Editing jTree1.setCellEditor (new DefaultTreeCellEditor(jTree1, new DefaultTreeCellRenderer(), new DefaultCellEditor(jcboColor)));

53 Liang, Introduction to Java Programming, Fifth Edition, (c) 2005 Pearson Education, Inc. All rights reserved. 0-13-148952-6 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.


Download ppt "Liang, Introduction to Java Programming, Fifth Edition, (c) 2005 Pearson Education, Inc. All rights reserved. 0-13-148952-6 1 Chapter 24 Advanced Swing."

Similar presentations


Ads by Google