Level: Intermediate Brett Spell (JavaBrewer@aol.com)Wrox Press Ltd
01 Nov 2000 The book Professional Java Programming covers a variety of advanced Java topics, such as the Java 2 security model, internationalization, performance tuning and memory management, printing, help, drag-and-drop operations, and cut-and-paste operations. It also contains chapters on JTree and JTable, two of the more complex components provided with Swing. This excerpt from Chapter 6 explains how JTable handles the drawing (or "rendering") of its cells and supports the editing of their values. In addition to describing the behavior of the renderers and editors provided with Swing, the text also discusses how to go about creating your own implementations. The complete chapter in the book includes information on how to enhance JTable's functionality to add features that are often needed, such as the ability to sort rows, to create multi-line column headers, and so on. Cell rendering In the screen shot below, the data in several of the columns isn't displayed in an ideal fashion:
Specifically, three things can be improved: - The Date of Birth column displays both a date and time, but should only display a date, and that date should be in a format that does not include the day of the week.
- Account Balance displays a simple numeric value, but should use currency-formatting conventions.
- The Gender column displays a somewhat non-intuitive value of "true" or "false" instead of "Male" or "Female."
JTable cells are drawn by cell renderers, which are classes that implement the TableCellRenderer interface. That interface defines a single getTableCellRendererComponent() method that returns a reference to the Component that will perform the drawing operation. However, since it's often convenient to define a single class that implements TableCellRenderer and that can perform the rendering, a TableCellRenderer will often simply return a reference to itself. The parameters passed to getTableCellRendererComponent() are: - A reference to the
JTable that contains the cell being drawn - A reference to the cell's value
- A
boolean flag that indicates whether or not the cell is selected - A
boolean flag that indicates whether or not the cell has the input focus - The row index of the cell being drawn
- The column index of the cell being drawn
In addition to returning a reference to the rendering component, getTableCellRendererComponent() is responsible for initializing the component's state. Notice that one of the parameters listed above is a reference to the value stored in the cell that's about to be rendered, and some representation of that value is usually stored in the rendering component before a reference to it is returned. As we'll see shortly, JTable provides predefined renderers that you can use to have your data displayed properly, but first we'll look at how easily custom renderer classes can be defined.
Creating custom renderers The following class provides an example of a custom renderer, and it will be used to display the values in the Gender field in our sample application's table. Those values currently appear as a text string of "true" or "false" depending upon the cell's value, but this renderer will cause them to be drawn by a JComboBox :
import java.awt.Component; import javax.swing.JComboBox; import javax.swing.JTable; import javax.swing.table.TableCellRenderer;
public class GenderRenderer extends JComboBox implements TableCellRenderer {
public GenderRenderer() { super(); addItem("Male"); addItem("Female"); }
public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) {
if (isSelected) { setForeground(table.getSelectionForeground()); super.setBackground(table.getSelectionBackground()); } else { setForeground(table.getForeground()); setBackground(table.getBackground()); }
boolean isMale = ((Boolean) value).booleanValue(); setSelectedIndex(isMale ? 0 : 1); return this; }
}
|
When an instance of this class is created, it adds two items to its list: a "Male" selection, and a "Female" selection. The getTableCellRendererComponent() method performs some simple color selection for the foreground and background, and then selects the appropriate gender based on the cell's value ("Male" for true , "Female" for false ). Once this renderer class has been created, you can specify that it should be used for the Gender column by making the following changes to SimpleTableTest :
import java.awt.*; import javax.swing.*; import javax.swing.table.*;
public class SimpleTableTest extends JFrame {
protected JTable table;
public static void main(String[] args) { SimpleTableTest stt = new SimpleTableTest(); stt.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); stt.setSize(400, 300); stt.setVisible(true); }
public SimpleTableTest() { Container pane = getContentPane(); pane.setLayout(new BorderLayout()); TableValues tv = new TableValues(); table = new JTable(tv); TableColumnModel tcm = table.getColumnModel(); TableColumn tc = tcm.getColumn(TableValues.GENDER); tc.setCellRenderer(new GenderRenderer()); JScrollPane jsp = new JScrollPane(table); pane.add(jsp, BorderLayout.CENTER); }
}
|
The data for the table comes from the TableValues class (though in a real application it would probably come from a database):
import java.util.Calendar; import java.util.GregorianCalendar; import javax.swing.table.AbstractTableModel;
public class TableValues extends AbstractTableModel {
public final static int FIRST_NAME = 0; public final static int LAST_NAME = 1; public final static int DATE_OF_BIRTH = 2; public final static int ACCOUNT_BALANCE = 3; public final static int GENDER = 4;
public final static boolean GENDER_MALE = true; public final static boolean GENDER_FEMALE = false;
public final static String[] columnNames = { "First Name", "Last Name", "Date of Birth", "Account Balance", "Gender" };
public Object[][] values = { { "Clay", "Ashworth", new GregorianCalendar(1962, Calendar.FEBRUARY, 20).getTime(), new Float(12345.67), new Boolean(GENDER_MALE) }, { "Jacob", "Ashworth", new GregorianCalendar(1987, Calendar.JANUARY, 6).getTime(), new Float(23456.78), new Boolean(GENDER_MALE) }, { "Jordan", "Ashworth", new GregorianCalendar(1989, Calendar.AUGUST, 31).getTime(), new Float(34567.89), new Boolean(GENDER_FEMALE) }, { "Evelyn", "Kirk", new GregorianCalendar(1945, Calendar.JANUARY, 16).getTime(), new Float(-456.70), new Boolean(GENDER_FEMALE) }, { "Belle", "Spyres", new GregorianCalendar(1907, Calendar.AUGUST, 2).getTime(), new Float(567.00), new Boolean(GENDER_FEMALE) } };
public int getRowCount() { return values.length; }
public int getColumnCount() { return values[0].length; }
public Object getValueAt(int row, int column) { return values[row][column]; }
public String getColumnName(int column) { return columnNames[column]; }
}
|
When you compile and execute the modified version of the application, it produces a display like the one shown below. Notice that the "true" and "false" strings that previously appeared in the Gender column now seem to have been replaced by instances of JCheckBox :
It's important to realize that renderers are not really added to JTable instances the way that visual components are added to a Container , which in this case means that the table doesn't contain any instances of JCheckBox . Instead, when the table is painted, each cell delegates responsibility for drawing its contents, which is done by passing a Graphics object to a renderer component's paint() method, and the drawing region is set to correspond to the area occupied by the cell. In other words, no instances of JCheckBox were added to the JTable in this example, but rather a single instance of JCheckBox drew itself onto the area occupied by each cell in the Gender column. This approach may seem unnecessarily complex, but it allows a single component to draw most or all of a table's cells instead of requiring the table to allocate a component for each cell, which would consume far more memory. In many cases, the easiest way to define a custom cell renderer is to extend Swing's DefaultTableCellRenderer , which as its name implies is the default renderer for cells in a JTable . DefaultTableCellRenderer extends JLabel and it displays cell values using their String representations. An object's String representation is obtained by calling its toString() method, and DefaultTableCellRenderer passes that representation to the setText() method it inherits from JLabel . This behavior is implemented in the setValue() method, which is passed a reference to the value of the cell that's about to be rendered:
protected void setValue(Object value) { setText((value == null) ? "" : value.toString()); }
|
In effect, DefaultTableCellRenderer is simply a JLabel that sets its own text based on the value of the cell being rendered. In many cases, calling toString() isn't an appropriate way to obtain a representation of the cell's value, and an example of this is the Account Balance column in our sample application. The values displayed in that column are technically correct, but they're not formatted in a manner that makes it obvious that they represent currency values. However, this can easily be addressed by creating a custom TableCellRenderer and assigning it responsibility for drawing the cells in that column.
import java.text.NumberFormat; import javax.swing.table.DefaultTableCellRenderer;
public class CurrencyRenderer extends DefaultTableCellRenderer {
public CurrencyRenderer() { super(); setHorizontalAlignment(javax.swing.SwingConstants.RIGHT); }
public void setValue(Object value) { if ((value != null) && (value instanceof Number)) { Number numberValue = (Number) value; NumberFormat formatter = NumberFormat.getCurrencyInstance(); value = formatter.format(numberValue.doubleValue()); } super.setValue(value); }
}
|
This simple class does just two things: it changes the label's horizontal alignment during construction, and it overrides the setValue() method defined in DefaultTableCellRenderer . Since we know that this renderer class will only be used to render the cells containing numeric values, we can cast the cell's value to a Number and then format the value as a currency using Java's NumberFormat class. Now that we've created a custom renderer for the Account Balance column, we need to have the table use the renderer when drawing the cells in that column, which could be done by explicitly assigning it to the TableColumn as we did in the previous example. However, there is another way to accomplish this that's worth mentioning and which is more appropriate in many cases. Besides associating a renderer with a particular column, you can also associate it with a particular type of data, and the renderer will then be used to draw all cells in columns that contain that type of data. When a JTable is initialized, it creates a map that defines associations between classes and renderers, and it uses that map to select a cell renderer when drawing cells in columns for which no renderer was explicitly set. In other words, if you have not explicitly assigned a renderer to a column as we did earlier, JTable will select a renderer based upon the type of data stored in that column. It determines the column's data type by calling the getColumnClass() method in the TableModel , and that method returns an instance of Class. However, the implementation of getColumnClass() in AbstractTableModel simply indicates that all its columns contain instances of Object as shown below:
public Class getColumnClass(int columnIndex) { return Object.class; }
|
Since AbstractTableModel can't know what kind of data its subclasses will contain, the only assumption that it can safely make is that each cell contains an instance of Object , although in practice, the cells will almost certainly contain instances of some subclass of Object such as Float , Date , etc. Therefore, if you want the table to be able to determine the specific type of data its columns contain, you must override getColumnClass() in your TableModel class. For example, since all of the values in the Account Balance column are instances of Float , we could add the following getColumnClass() implementation to the TableValues class:
public Class getColumnClass(int column) { Class dataType = super.getColumnClass(column); if (column == ACCOUNT_BALANCE) { dataType = Float.class; } return dataType; }
|
Now that our JTable is able to determine that the Account Balance column contains Float data, we need to associate our CurrencyRenderer class with that data type, which can easily be done by calling setDefaultRenderer() as shown below:
public SimpleTableTest() { Container pane = getContentPane(); pane.setLayout(new BorderLayout()); TableValues tv = new TableValues(); table = new JTable(tv); TableColumnModel tcm = table.getColumnModel(); TableColumn tc = tcm.getColumn(TableValues.GENDER); tc.setCellRenderer(new GenderRenderer()); table.setDefaultRenderer(Float.class, new CurrencyRenderer()); JScrollPane jsp = new JScrollPane(table); pane.add(jsp, BorderLayout.CENTER); }
|
This new addition to SimpleTableTest causes CurrencyRenderer to become the default renderer for all columns containing Float data. Therefore, CurrencyRenderer will be used to draw the cells in the Account Balance column because no renderer was assigned to the column and because getColumnClass() now indicates that the column contains Float data. An example of how the interface will appear when the program is executed with these modifications is shown below:
At this point, you may be wondering what happens when no renderer has been explicitly assigned to a column and there is no entry in the table's class-to-renderer map that matches the column's data type. You're correct if you guessed that the rendering is handled by DefaultTableCellRenderer , but it's important to understand exactly how that occurs. When no renderer has been explicitly assigned to a column and no entry for the column's Class is found in the table's class-to-renderer map, JTable traverses the inheritance hierarchy of the column's Class , searching the class-to-renderer map for an entry corresponding to each superclass until it locates one. For example, if getColumnClass() indicates that the column contains Float data but no entry for Float is found in the class-to-renderer map, JTable next attempts to locate a map entry that corresponds to Float 's immediate superclass, which is Number . If it does not find an entry for Number , it will attempt to retrieve an entry for Object (Number 's immediate superclass), which will always succeed because the map automatically contains an entry that associates Object columns with DefaultTableCellRenderer . To summarize JTable 's behavior, the steps for locating a renderer are listed below: - If a renderer has been set for the cell's
TableColumn , use that renderer. - Obtain a reference to a
Class instance by calling the TableModel 's getColumnClass() method. - If a renderer has been mapped to that
Class , use that renderer. - Obtain a reference to the
Class instance of the type's superclass and repeat the previous step until a match is found.
This approach provides a great deal of flexibility in assigning renderers to table cells, since it allows you to create a renderer and have it handle rendering for columns with a specific data type, along with any subclasses of that type.
JTable's default renderers We've now seen how to create custom renderers and how to associate a renderer with a given type of data. However, it's often not necessary to do either one, since JTable includes a number of predefined renderers for commonly used data types, and entries for those renderers are automatically included in its class-to-renderer map. For example, it was already mentioned that an entry exists in the map that associates Object columns with DefaultTableCellRenderer , but other, more sophisticated renderers are provided as well. This means that if one of the predefined renderers is appropriate for your application, the only coding you need to do is to identify your columns' data types in an implementation of getColumnClass() so that JTable will use the appropriate renderers. To illustrate this point, we'll use JTable 's predefined renderer for instances of java.util.Date by simply modifying TableValues so that it indicates that the Date of Birth column contains instances of Date :
public Class getColumnClass(int column) { Class dataType = super.getColumnClass(column); if (column == ACCOUNT_BALANCE) { dataType = Float.class; } else if (column == DATE_OF_BIRTH) { dataType = java.util.Date.class; } return dataType; }
|
As we saw earlier, the date values displayed by DefaultTableCellRenderer were lengthy and included a time (since Java's Date class represents both a date and a time). However, JTable 's predefined date renderer produces a shorter, more appropriate representation of each date value as shown below:
In addition to java.util.Date , JTable includes predefined renderers for a number of other classes, including the following: java.lang.Number This is the superclass of the numeric wrappers such as Integer , Float , Long , etc. The renderer that's defined for Number is a subclass of DefaultTableCellRenderer that simply sets its alignment value to RIGHT as we did in CurrencyRenderer . In other words, the Number renderer displays the toString() representation of the cell values, but it displays the text adjacent to the right side of the cell instead of the left (the default). An example of how this would appear if used with the Account Balance column in the SampleTableTest class is shown below:
javax.swing.ImageIcon The renderer associated with this class allows you to display instances of ImageIcon within a table. The renderer is simply an instance of DefaultTableCellRenderer that takes advantage of the fact that a JLabel can contain both text and an icon. Instead of rendering the cell by setting its text value, this renderer sets its icon instead. java.lang.Boolean When this renderer is used, it displays the value for the cell as a JCheckBox that is either checked (when the cell's value is true) or unchecked (when the value is false). An example of how it would appear if used with the Gender column SimpleTableTest is shown below:
Editing table cells Although each cell in the Gender column now appears to be a JComboBox , it's not possible to change the gender that's selected. In fact, none of the cells in the table is editable, and clicking on them merely causes the row to be selected. To change this behavior, you must override the isCellEditable() method, because the implementation in DefaultTableModel always returns false . However, this can be changed easily by adding the following code to TableValues :
public boolean isCellEditable(int row, int column) { if (column == GENDER) { return true; } return false; }
|
This indicates that the cells in the Gender column are now editable. However, if you click on a cell in that column intending to select a gender from a JComboBox , you may be surprised to find that nothing happens except that the row you clicked on becomes selected. If you double-click on the cell, a JTextField appears that is initialized with the string equivalent of the cell's Boolean value ("true" or "false") and you can edit the data in the text field:
You may be surprised that a text field appears when you edit the cell, because the cell seems to contain a JComboBox , but remember that table cells don't actually contain any components. The cells are simply drawn by components (the renderers), and in this case, the component happens to be a JComboBox . However, editing is a completely separate process that may or may not be handled by the same type of component that performed the rendering. For example, the default rendering component used by JTable is a JLabel , while the default editing component is a JTextField , which is why a text field appeared in this case. Regardless of which type of component is used, it may seem that the cells are finally editable, which is partly true, but if you enter a value into one of these cells, the value you type is discarded once you complete the editing. To understand why this occurs and what to do about it, you should be familiar with cell editors and how JTable handles the editing of its cells. Cell editors Just as cell renderers control the way that a cell's values are drawn, cell editors handle cell value editing. Editors are slightly more complex than renderers, but have many similarities to renderers: - An editor can be assigned to one or more
TableColumn instances. - An editor can be associated with one or more data types (classes), and will be used to display that type of data when no editor is associated with a cell's column.
- Existing visual components are used to provide editing capabilities, just as they are used by renderers to draw cell values. In fact, the same type of visual component that's used as a cell's renderer is often used for its editor as well. For example, a cell might be assigned a renderer that uses a
JComboBox and an editor that uses the same component.
You can assign an editor to one or more TableColumn instances or object types using the setCellEditor() method in TableColumn and setDefaultEditor() in JTable , respectively. However, the implementation of the TableCellEditor interface is more complex than TableCellRenderer , and to understand the methods defined in TableCellEditor , it's useful to examine how editors interact with JTable instances. When a JTable detects a mouse click over one of its cells, it calls the isCellEditable() method in the TableModel . That method returns a value of false if the cell should not be editable, in which case processing terminates and no further action is taken. However, if the method returns true , then the table identifies the cell editor for that cell and calls the CellEditor 's isCellEditable() method as well. Although TableModel and CellEditor both define methods called isCellEditable() , there is an important difference between the two. Specifically, the TableModel method is only passed row and column index values, while the CellEditor method is also passed the EventObject representing the mouse click. This can be used, for example, to check the "click count" stored in the event. A cell must be double-clicked before it is edited, as observed earlier when editing the Gender column values. In other words, the isCellEditable() method returns a value of false when the click count is 1, while it returns true if the count is greater than 1. This behavior allows the cell editor to distinguish between a request to select the cell (a single-click) and a request to edit the cell (a double-click). The edit operation is allowed to proceed only if both the TableModel 's and the CellEditor 's isCellEditable() method return a value of true. When that's the case, the editing is initiated by calling the getTableCellEditorComponent() method, which is passed the following parameters: - A reference to the
JTable that contains the cell being edited - A reference to the cell's current value
- A
boolean flag that indicates whether or not the cell is selected - The row index of the cell being edited
- The column index of the cell being edited
If these parameters look familiar, it's because they're almost identical to those passed to the getTableCellRendererComponent() method in TableCellRenderer . The only difference is that this method is not passed a boolean value indicating whether or not the cell has the input focus, since that is implied by the fact that the cell is being edited. Before returning a reference to the component that's responsible for handling editing, getTableCellEditorComponent() should prepare the editor by initializing its value appropriately so that it matches the current cell value. For example, let's assume that we're creating an editor that allows users to select either "Male" or "Female" from a JComboBox that represents the Gender column value in TableValues . In that case, the JComboBox that performs the editing should be prepared by selecting the item it contains that corresponds to the cell's gender value: "Male" if the cell's value is true, "Female" if the value is false. Once the editing component has been prepared and returned from the getTableCellEditorComponent() method, the JTable sets the size and location of that component so that it's directly "over" the cell being edited. This makes it appear that the cell is edited in place, when in fact, a component that supports editing (such as a JTextField or in this case, a JComboBox ) has been superimposed over the cell. With the editing component positioned over the cell being edited, the event that originally triggered the edit processing is posted to the editing component. For example, in the case of a JComboBox -based editor, the same mouse event that initiated the editing is passed to the combo box, possibly causing it to display its drop-down menu when editing starts. Finally, the CellEditor 's shouldSelectCell() method is passed the same mouse event object, and if it returns true, the cell (and possibly others, depending upon the table's selection settings) is selected. Each CellEditor is required to implement the addCellEditorListener() and removeCellEditorListener() methods, and the CellEditorListener interface defines two methods: editingStopped() and editingCanceled() . In practice, the only listener is usually the JTable itself, which is notified when editing is stopped or canceled. In addition, the CellEditor must implement the cancelCellEditing() and stopCellEditing() methods, which call the editingStopped() and editingCanceled() methods of registered listeners. A request to end editing can come either from the JTable that contains the cell, or from the editor component itself. For example, suppose that you click on one cell and begin editing its value. If you then click on a different cell, the JTable calls the stopCellEditing() method of the first cell's editor before it initiates editing of the second cell. Alternatively, the editor component may stop the editing when some event occurs that implies that editing is complete. For example, when using a JComboBox as an editor, if it receives an ActionEvent message indicating that a selection was made, then it's appropriate to terminate the edit. Similarly, a JTextField might signal that editing has ended when it detects that the Return key was pressed. Regardless of where the request originates to end editing, the JTable 's editingStopped() method is called since it is a registered CellEditorListener . Inside this method, the table calls the editor's getCellEditorValue() method to retrieve the cell's new value and passes that value to the setValueAt() method in the JTable 's TableModel . That is, it retrieves the cell's new value from the editor and sends it to the data model so that it can be stored "permanently." The following class defines a component that can be used to provide editing of the rows in the Gender column defined in TableValues . It defines a subclass of JComboBox that initializes itself with "Male" and "Female" entries and listens for changes to its state (waits for a selection to be made). When editing is initiated for one of the cells in the Gender column, the getTableCellEditorComponent() method is called, giving the editor a chance to initialize its state before it is made visible. In this case, the editor simply makes either "Male" or "Female" the selected entry based on the value stored in the cell being edited. When the user selects an item in the JComboBox , fireEditingStopped() is called, which signals to the table that the edit session has ended. The table will then call getCellEditorValue() to retrieve the new value that should be stored in the cell and will pass that value to the TableModel 's setValueAt() method.
import java.awt.Component; import java.util.EventObject; import java.awt.event.*; import javax.swing.*; import javax.swing.event.*; import javax.swing.table.*;
public class GenderEditor extends JComboBox implements TableCellEditor {
protected EventListenerList listenerList = new EventListenerList(); protected ChangeEvent changeEvent = new ChangeEvent(this);
public GenderEditor() { super(); addItem("Male"); addItem("Female"); addActionListener(new ActionListener() { public void actionPerformed(ActionEvent event) { fireEditingStopped(); } }); }
public void addCellEditorListener(CellEditorListener listener) { listenerList.add(CellEditorListener.class, listener); }
public void removeCellEditorListener(CellEditorListener listener) { listenerList.remove(CellEditorListener.class, listener); }
protected void fireEditingStopped() { CellEditorListener listener; Object[] listeners = listenerList.getListenerList(); for (int i = 0; i < listeners.length; i++) { if (listeners[i] == CellEditorListener.class) { listener = (CellEditorListener) listeners[i + 1]; listener.editingStopped(changeEvent); } } }
protected void fireEditingCanceled() { CellEditorListener listener; Object[] listeners = listenerList.getListenerList(); for (int i = 0; i < listeners.length; i++) { if (listeners[i] == CellEditorListener.class) { listener = (CellEditorListener) listeners[i + 1]; listener.editingCanceled(changeEvent); } } }
public void cancelCellEditing() { fireEditingCanceled(); }
public boolean stopCellEditing() { fireEditingStopped(); return true; }
public boolean isCellEditable(EventObject event) { return true; }
public boolean shouldSelectCell(EventObject event) { return true; }
public Object getCellEditorValue() { return new Boolean(getSelectedIndex() == 0 ? true : false); }
public Component getTableCellEditorComponent(JTable table, Object value, boolean isSelected, int row, int column) { boolean isMale = ((Boolean) value).booleanValue(); setSelectedIndex(isMale ? 0 : 1); return this; }
}
|
Now that the editor component has been defined, it needs to be associated with the Gender column, as shown in the following code:
public SimpleTableTest() { Container pane = getContentPane(); pane.setLayout(new BorderLayout()); TableValues tv = new TableValues(); table = new JTable(tv); TableColumnModel tcm = table.getColumnModel(); TableColumn tc = tcm.getColumn(TableValues.GENDER); tc.setCellRenderer(new GenderRenderer()); tc.setCellEditor(new GenderEditor()); table.setDefaultRenderer(Float.class, new CurrencyRenderer()); JScrollPane jsp = new JScrollPane(table); pane.add(jsp, BorderLayout.CENTER); }
|
When this code is compiled and run, a JComboBox correctly appears, is initialized with the appropriate gender value, and allows you to select either "Male" or "Female":
However, selecting a different value from the one already stored in the cell does not result in the cell's value being modified. That's because the value is never changed in the TableModel , which is done by implementing the setValueAt() method in the TableValues class:
public void setValueAt(Object value, int row, int column) { values[row][column] = value; }
|
DefaultCellEditor It's not necessary in every case to build a completely new cell editor. In fact, the DefaultCellEditor class allows you to easily create editor components using a JCheckBox , JComboBox , or JTextField . All that's necessary is to create an instance of DefaultCellEditor and pass it an instance of one of these three components. However, the DefaultCellEditor is not very flexible, and you'll often need to create your own editor as was done in this case.
Resources
|
No comments:
Post a Comment