Creating Your Own Editors
In addition to letting you customize the rendering of cells, the table component allows you to attach custom cell editors to columns of cells. As a result, you can edit cell values in different ways. To see what a cell editor looks like, take a look at Figure 12.
Figure 12 Because a table component supports custom column editing, you can edit true/false values using a more natural editor, such as a check box.
As with TableDemo10, the TableDemo12 program that generated Figure 12 was not hard to write because it relies on one of a table component's default editors. To see what TableDemo12's source code looks like, examine Listing 12.
Listing 12: TableDemo12.java
// TableDemo12.java import java.awt.*; import javax.swing.*; import javax.swing.table.DefaultTableModel; class TableDemo12 extends JFrame { TableDemo12 (String title) { // Pass the title to the JFrame superclass so that it appears in // the title bar. super (title); // Tell the program to exit when the user either selects Close // from the System menu or presses an appropriate X button on the // title bar. setDefaultCloseOperation (EXIT_ON_CLOSE); // Create a my table model consisting of 4 rows by 3 columns. MyTableModel mtm = new MyTableModel (4, 3); // Assign column identifiers (headers) to the columns. String [] columnTitles = { "Name", "Address", "Unemployed", }; mtm.setColumnIdentifiers (columnTitles); // Populate all cells in the my table model. String [] names = { "John Doe", "Jane Smith", "Jack Jones", "Paul Finch" }; String [] addresses = { "200 Fox Street", "Apt. 555", "Box 9000", "1888 Apple Avenue" }; Boolean [] employmentStatus = { new Boolean (false), new Boolean (true), new Boolean (false), new Boolean (true) }; int nrows = mtm.getRowCount (); for (int i = 0; i < nrows; i++) { mtm.setValueAt (names [i], i, 0); mtm.setValueAt (addresses [i], i, 1); mtm.setValueAt (employmentStatus [i], i, 2); } // Create a table using the previously created my table model. JTable jt = new JTable (mtm); // Place the table in a JScrollPane object (to allow the table to // be vertically scrolled and display scrollbars, as necessary). JScrollPane jsp = new JScrollPane (jt); // Add the JScrollPane object to the frame window's content pane. // That allows the table to be displayed within a displayed // scroll pane. getContentPane ().add (jsp); // Establish the overall size of the frame window to 400 // horizontal pixels by 110 vertical pixels. setSize (400, 110); // Display the frame window and all contained // components/containers. setVisible (true); } public static void main (String [] args) { // Create a TableDemo12 object, which creates the GUI. new TableDemo12 ("Table Demo #12"); } } class MyTableModel extends DefaultTableModel { MyTableModel (int rows, int cols) { super (rows, cols); } public Class getColumnClass (int columnIndex) { // If column is the Unemployed column, return Boolean.class so // that the Boolean renderer and editor will be used. if (columnIndex == 2) return Boolean.class; else return Object.class; } }
Because TableDemo12 is so similar to TableDemo10 in structure, there really isn't much to say about the code. However, you might find it interesting to note that the table component chooses both a Boolean renderer and a Boolean editor when getColumnClass(int columnIndex) returns Boolean.class for the third column. In fact, each default renderer has its own corresponding default editor. Apart from the Boolean default editor, the other default editors don't look much different from the Object.class default editor.
Editors in Depth
Although it's nice to be able to use a default editor, there are times when you want to add your own custom editor. For example, you might want to modify TableDemo10 so that it allows you to pick colors from a color chooser, instead of forcing you to modify a cell's string text. As you might have guessed, you will be given an opportunity to see a TableDemo13 program that extends TableDemo10 with such an editor. However, before you can see that program, you need to understand how a table component deals with the editing task.
A table component's UI delegate (such as BasicTableUI) initiates editing in one of two ways. First, if you press any key other than F2 (and some special keys, such as the arrow keys), JTable's processKeyBinding(KeyStroke ks, KeyEvent e, int condition, boolean pressed) method automatically starts the editor for the focused cell. Second, if you press F2 or double-click the left mouse button while the mouse pointer is positioned over some cell, an action named startEditing is invoked. Specifically, its actionPerformed(ActionEvent e) method gets called and starts the editor for the focused cell. Regardless, JTable's editCellAt(int rowIndex, int columnIndex) method is called with the row and column indexes of the focused cell.
The editCellAt(int rowIndex, int columnIndex) method calls JTable's editCellAt(int rowIndex, int columnIndex, EventObject e) method with null assigned to e. That latter method first determines whether the cell at (rowIndex, columnIndex) is read-only by calling JTable's isCellEditable(int rowIndex, int columnIndex) convenience method. If that cell is read-only, editCellAt(int rowIndex, int columnIndex, EventObject e) returns and the cell is not edited.
Assuming that the cell is editable, editCellAt(int rowIndex, int columnIndex, EventObject e) calls JTable's getCellEditor(int rowIndex, int columnIndex) method to return a reference to an object whose class implements the TableCellEditor interface. That object serves as the cell's editor. The following source code (taken from the JTable class) shows how getCellEditor(int rowIndex, int columnIndex) works:
public TableCellEditor getCellEditor(int row, int column) { // Acquire a reference to the TableColumn object associated with // column. TableColumn tableColumn = getColumnModel ().getColumn (column); // Fetch the editor associated with the TableColumn object. TableCellEditor editor = tableColumn.getCellEditor (); // If the developer has not specified an editor for that column, // obtain a reference to the default editor. if (editor == null) editor = getDefaultEditor (getColumnClass (column)); return editor; }
If getCellEditor(rowIndex, columnIndex) returns a non-null reference to an editor, and if editing can start on that cell, editCellAt(int rowIndex, int columnIndex, EventObject e) calls JTable's prepareEditor(TableCellEditor editor, int rowIndex, int columnIndex) method to prepare the editor for editing. The following code fragment (taken from JTable's prepareEditor(TableCellEditor editor, int rowIndex, int columnIndex) method) shows what happens:
Object value = getValueAt (rowIndex, columnIndex); boolean isSelected = isCellSelected (rowIndex, columnIndex); Component comp = editor.getTableCellEditorComponent (this, value, isSelected, row, column);
First, JTable's getValueAt(int rowIndex, int columnIndex) convenience method is called to retrieve the value located at (rowIndex, columnIndex) in the data model. Then JTable's isCellSelected(rowIndex, columnIndex) method is called to determine whether that cell has been selected so that an appropriate selection rectangle can be drawn. Finally, the editor's getTableCellEditorComponent(JTable table, Object value, boolean isSelected, int rowIndex, int columnIndex) method is called to configure the editor and return a Component object that carries out the editing. That object's reference returns from prepareEditor(TableCellEditor editor, int rowIndex, int columnIndex).
Assuming that a non-null Component reference returns, editCellAt(int rowIndex, int columnIndex, EventObject e) calls several methods to initialize the editor. One of those methods attaches a CellEditorListener to the editor. The listener responds to various events, such as editing canceled and editing stopped. If an editing stopped event occurs, the value is read from the editor (via the editor's getCellEditorValue() method) and stored in the model (via the model's setValueAt(Object value, int rowIndex, int columnIndex) method.
You can create your own editor either by subclassing the AbstractCellEditor class and implementing the TableCellEditor interface or by subclassing the DefaultCellEditor class. Listing 13's TableDemo13 source code demonstrates the former approach.
Listing 13: TableDemo13.java
// TableDemo13.java import java.awt.*; import javax.swing.*; import javax.swing.table.*; class TableDemo13 extends JFrame { TableDemo13 (String title) { // Pass the title to the JFrame superclass so that it appears in // the title bar. super (title); // Tell the program to exit when the user either selects Close // from the System menu or presses an appropriate X button on the // title bar. setDefaultCloseOperation (EXIT_ON_CLOSE); // Create a my table model consisting of 4 rows by 3 columns. MyTableModel mtm = new MyTableModel (4, 3); // Assign column identifiers (headers) to the columns. String [] columnTitles = { "Name", "Address", "Favorite Color", }; mtm.setColumnIdentifiers (columnTitles); // Populate all cells in the my table model. String [] names = { "John Doe", "Jane Smith", "Jack Jones", "Paul Finch" }; String [] addresses = { "200 Fox Street", "Apt. 555", "Box 9000", "1888 Apple Avenue" }; Color [] favoriteColors = { Color.red, Color.blue, Color.green, Color.red }; int nrows = mtm.getRowCount (); for (int i = 0; i < nrows; i++) { mtm.setValueAt (names [i], i, 0); mtm.setValueAt (addresses [i], i, 1); mtm.setValueAt (favoriteColors [i], i, 2); } // Create a table using the previously created default table // model. JTable jt = new JTable (mtm); // Establish a color renderer for the third column. jt.getColumnModel ().getColumn (2). setCellRenderer (new ColorRenderer()); // Establish a color editor for the third column. jt.getColumnModel ().getColumn (2). setCellEditor (new ColorEditor ()); // Place the table in a JScrollPane object (to allow the table to // be vertically scrolled and display scrollbars, as necessary). JScrollPane jsp = new JScrollPane (jt); // Add the JScrollPane object to the frame window's content pane. // That allows the table to be displayed within a displayed // scroll pane. getContentPane ().add (jsp); // Establish the overall size of the frame window to 400 // horizontal pixels by 110 vertical pixels. setSize (400, 110); // Display the frame window and all contained // components/containers. setVisible (true); } public static void main (String [] args) { // Create a TableDemo13 object, which creates the GUI. new TableDemo13 ("Table Demo #13"); } } class ColorEditor extends AbstractCellEditor implements TableCellEditor { private JLabel l = new JLabel (""); public Object getCellEditorValue () { // Return the label's background color so that it can be stored // in the table component's model. return l.getBackground (); } public Component getTableCellEditorComponent (JTable table, Object value, boolean isSelected, int row, int column) { if (value instanceof Color) { // Display a JColorChooser dialog box that allows the user to // choose a color from a visual color picker. Color c = JColorChooser.showDialog (null, "Choose color", (Color) value); // If user didn't Cancel the Color Chooser, set the label's // background to the chosen color, as expressed via a Color // object. Otherwise, assign the Color object, as expressed // by value, to the label's background. If that is not done, // a future return l.getBackground (); in // getCellEditorValue() will return the most recently set // background color, which will then be assigned to the table // component's model. That color will most likely not be the // same as the color passed in value. As a result, a cell's // original background color will disappear. if (c != null) l.setBackground (c); else l.setBackground ((Color) value); } // Return a reference to the component that does the editing. // Because a JLabel reference is being returned, there won't be // any editing. The reason editing isn't needed is that the color // chooser is being used to obtain the color. return l; } } class ColorRenderer extends DefaultTableCellRenderer { public Component getTableCellRendererComponent (JTable table, Object value, boolean isSelected, boolean isFocus, int row, int column) { if (value instanceof Color) setBackground ((Color) value); // Prevent value.toString ()'s returned String from being // rendered. value = ""; // Allow the superclass to complete configuring the renderer. return super.getTableCellRendererComponent (table, value, isSelected, isFocus, row, column); } } class MyTableModel extends DefaultTableModel { MyTableModel (int rows, int cols) { super (rows, cols); } public Class getColumnClass (int columnIndex) { // If column is the Favorite color column, return Color.class so // that the Color renderer and editor will be used. if (columnIndex == 2) return Color.class; else return Object.class; } }
When you run TableDemo13, you see a table component consisting of three columns. The rightmost column displays colored cells, thanks to the ColorRenderer. If you double-click (or even single-click) on one of those colored cellsor if you press F2 when one of those cells is focused, a color chooser dialog box appears as an editor and allows you to select a replacement color. Assuming that you click the color chooser's OK button after selecting a color, you will not see the new color until you select a different row. However, if you cancel the color chooser, the cell's original color will remain.