18.3. TablesTables present information in orderly rows and columns. This is useful for presenting financial figures or representing data from a relational database. Like trees, tables in Swing are incredibly powerful and customizable. If you go with the default options, they're also pretty easy to use. The JTable class represents a visual table component. A JTable is based on a TableModel, one of a dozen or so supporting interfaces and classes in the javax.swing.table package. 18.3.1. A First Stab: FreeloadingJTable has one constructor that creates a default table model for you from arrays of data. You just need to supply it with the names of your column headers and a 2D array of Objects representing the table's data. The first index selects the table's row; the second index selects the column. The following example shows how easy it is to get going with tables using this constructor: //file: DullShipTable.java import java.awt.*; import java.awt.event.*; import javax.swing.*; import javax.swing.table.*; public class DullShipTable { public static void main(String[] args) { // create some tabular data String[] headings = new String[] {"Number", "Hot?", "Origin", "Destination", "Ship Date", "Weight" }; Object[][] data = new Object[][] { { "100420", Boolean.FALSE, "Des Moines IA", "Spokane WA", "02/06/2000", new Float(450) }, { "202174", Boolean.TRUE, "Basking Ridge NJ", "Princeton NJ", "05/20/2000", new Float(1250) }, { "450877", Boolean.TRUE, "St. Paul MN", "Austin TX", "03/20/2000", new Float(1745) }, { "101891", Boolean.FALSE, "Boston MA", "Albany NY", "04/04/2000", new Float(88) } }; // create the data model and the JTable JTable table = new JTable(data, headings); JFrame frame = new JFrame("DullShipTable v1.0"); frame.getContentPane( ).add(new JScrollPane(table)); frame.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE ); frame.setSize(500, 200); frame.setVisible(true); } } This small application produces the display shown in Figure 18-7. Figure 18-7. A rudimentary JTableFor very little typing, we've gotten some pretty impressive stuff. Here are a few things that come for free:
Play with this for a while. It's fun. 18.3.2. Round Two: Creating a Table ModelJTable is a very powerful component. You get a lot of very nice behavior for free. However, the default settings are not quite what we wanted for this simple example. In particular, we intended the table entries to be read-only; they should not be editable. Also, we'd like entries in the Hot? column to be checkboxes instead of words. Finally, it would be nice if the Weight column were formatted appropriately for numbers rather than for text. To achieve more flexibility with JTable, we'll write our own data model by implementing the TableModel interface. Fortunately, Swing makes this easy by supplying a class that does most of the work, AbstractTableModel. To create a table model, we'll just subclass AbstractTableModel and override whatever behavior we want to change. At a minimum, all AbstractTableModel subclasses have to define the following three methods:
When the JTable needs data values, it calls the getValueAt( ) method in the table model. To get an idea of the total size of the table, JTable calls the getrowCount( ) and getColumnCount( ) methods in the table model. A very simple table model looks like this: public static class ShipTableModel extends AbstractTableModel { private Object[][] data = new Object[][] { { "100420", Boolean.FALSE, "Des Moines IA", "Spokane WA", "02/06/2000", new Float(450) }, { "202174", Boolean.TRUE, "Basking Ridge NJ", "Princeton NJ", "05/20/2000", new Float(1250) }, { "450877", Boolean.TRUE, "St. Paul MN", "Austin TX", "03/20/2000", new Float(1745) }, { "101891", Boolean.FALSE, "Boston MA", "Albany NY", "04/04/2000", new Float(88) } }; public int getRowCount( ) { return data.length; } public int getColumnCount( ) { return data[0].length; } public Object getValueAt(int row, int column) { return data[row][column]; } } We'd like to use the same column headings we used in the previous example. The table model supplies these through a method called getColumnName( ). We could add column headings to our simple table model like this: private String[] headings = new String[] { "Number", "Hot?", "Origin", "Destination", "Ship Date", "Weight" }; public String getColumnName(int column) { return headings[column]; } By default, AbstractTableModel makes all its cells noneditable, which is what we wanted. No changes need to be made for this. The final modification is to have the Hot? column and the Weight column formatted specially. To do this, we give our table model some knowledge about the column types. JTable automatically generates checkbox cells for Boolean column types and specially formatted number cells for Number types. To give the table model some intelligence about its column types, we override the getColumnClass( ) method. The JTable calls this method to determine the data type of each column. It may then represent the data in a special way. This table model returns the class of the item in the first row of its data: public Class getColumnClass(int column) { return data[0][column].getClass( ); } That's really all there is to do. The following complete example illustrates how you can use your own table model to create a JTable using the techniques just described: //file: ShipTable.java import java.awt.*; import java.awt.event.*; import javax.swing.*; import javax.swing.table.*; public class ShipTable { public static class ShipTableModel extends AbstractTableModel { private String[] headings = new String[] { "Number", "Hot?", "Origin", "Destination", "Ship Date", "Weight" }; private Object[][] data = new Object[][] { { "100420", Boolean.FALSE, "Des Moines IA", "Spokane WA", "02/06/2000", new Float(450) }, { "202174", Boolean.TRUE, "Basking Ridge NJ", "Princeton NJ", "05/20/2000", new Float(1250) }, { "450877", Boolean.TRUE, "St. Paul MN", "Austin TX", "03/20/2000", new Float(1745) }, { "101891", Boolean.FALSE, "Boston MA", "Albany NY", "04/04/2000", new Float(88) } }; public int getRowCount( ) { return data.length; } public int getColumnCount( ) { return data[0].length; } public Object getValueAt(int row, int column) { return data[row][column]; } public String getColumnName(int column) { return headings[column]; } public Class getColumnClass(int column) { return data[0][column].getClass( ); } } public static void main(String[] args) { // create the data model and the JTable TableModel model = new ShipTableModel( ); JTable table = new JTable(model); table.setAutoResizeMode(JTable.AUTO_RESIZE_OFF); JFrame frame = new JFrame("ShipTable v1.0"); frame.getContentPane( ).add(new JScrollPane(table)); frame.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE ); frame.setSize(500, 200); frame.setVisible(true); } } The running application is shown in Figure 18-8. Figure 18-8. Customizing a table18.3.3. Round Three: A Simple SpreadsheetTo illustrate just how powerful and flexible the separation of the data model from the GUI can be, we'll show a more complex model. In the following example, we'll implement a very slim but functional spreadsheet (see Figure 18-9) using almost no customization of the JTable. All of the data processing is in a TableModel called SpreadSheetModel. Figure 18-9. A simple spreadsheetOur spreadsheet does the expected stuffallowing you to enter numbers or mathematical expressions such as (A1*B2)+C3 into each cell.[1] All cell editing and updating is driven by the standard JTable. We implement the methods necessary to set and retrieve cell data. Of course, we don't do any real validation here, so it's easy to break our table. (For example, there is no check for circular dependencies, which may be undesirable.)
As you will see, the bulk of the code in this example is in the inner class used to parse the value of the equations in the cells. If you don't find this part interesting, you might want to skip ahead. But if you have never seen an example of this kind of parsing before, we think you will find it to be very cool. Through the magic of recursion and Java's powerful String manipulation, it takes us only about 50 lines of code to implement a parser capable of handling basic arithmetic with arbitrarily nested parentheses. Here's the code: //file: SpreadsheetModel.java import java.util.StringTokenizer; import javax.swing.*; import javax.swing.table.AbstractTableModel; import java.awt.event.*; public class SpreadsheetModel extends AbstractTableModel { Expression [][] data; public SpreadsheetModel( int rows, int cols ) { data = new Expression [rows][cols]; } public void setValueAt(Object value, int row, int col) { data[row][col] = new Expression( (String)value ); fireTableDataChanged( ); } public Object getValueAt( int row, int col ) { if ( data[row][col] != null ) try { return data[row][col].eval( ) + ""; } catch ( BadExpression e ) { return "Error"; } return ""; } public int getRowCount( ) { return data.length; } public int getColumnCount( ) { return data[0].length; } public boolean isCellEditable(int row, int col) { return true; } class Expression { String text; StringTokenizer tokens; String token; Expression( String text ) { this.text = text.trim( ); } float eval( ) throws BadExpression { tokens = new StringTokenizer( text, " */+-( )", true ); try { return sum( ); } catch ( Exception e ) { throw new BadExpression( ); } } private float sum( ) { float value = term( ); while( more( ) && match("+-") ) if ( match("+") ) { consume( ); value = value + term( ); } else { consume( ); value = value - term( ); } return value; } private float term( ) { float value = element( ); while( more( ) && match( "*/") ) if ( match("*") ) { consume( ); value = value * element( ); } else { consume( ); value = value / element( ); } return value; } private float element( ) { float value; if ( match( "(") ) { consume( ); value = sum( ); } else { String svalue; if ( Character.isLetter( token( ).charAt(0) ) ) { int col = findColumn( token( ).charAt(0) + "" ); int row = Character.digit( token( ).charAt(1), 10 ); svalue = (String)getValueAt( row, col ); } else svalue = token( ); value = Float.parseFloat( svalue ); } consume( ); // ")" or value token return value; } private String token( ) { if ( token == null ) while ( (token=tokens.nextToken( )).equals(" ") ); return token; } private void consume( ) { token = null; } private boolean match( String s ) { return s.indexOf( token( ) )!=-1; } private boolean more( ) { return tokens.hasMoreTokens( ); } } class BadExpression extends Exception { } public static void main( String [] args ) { JFrame frame = new JFrame("Excelsior!"); JTable table = new JTable( new SpreadsheetModel(15, 5) ); table.setPreferredScrollableViewportSize( table.getPreferredSize( ) ); table.setCellSelectionEnabled(true); frame.getContentPane( ).add( new JScrollPane( table ) ); frame.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE ); frame.pack( ); frame.show( ); } } Our model extends AbstractTableModel and overrides just a few methods. As you can see, our data is stored in a 2D array of Expression objects. The setValueAt( ) method of our model creates Expression objects from the strings typed by the user and stores them in the array. The getValueAt( ) method returns a value for a cell by calling the expression's eval( ) method. If the user enters some invalid text in a cell, a BadExpression exception is thrown, and the word "error" is placed in the cell as a value. The only other methods of TableModel we must override are getrowCount( ), getColumnCount( ), and isCellEditable( ) to determine the dimensions of the spreadsheet and to allow the user to edit the fields. That's it! The helper method findColumn( ) is inherited from the AbstractTableModel. Now on to the good stuff. We'll employ our old friend StringTokenizer to read the expression string as separate values and the mathematical symbols (+-*/( )) one by one. These tokens are then processed by the three parser methods: sum( ), term( ), and element( ). The methods call one another generally from the top down, but it might be easier to read them in reverse to see what's happening. At the bottom level, element( ) reads individual numeric values or cell namese.g., 5.0 or B2. Above that, the term( ) method operates on the values supplied by element( ) and applies any multiplication or division operations. And at the top, sum( ) operates on the values that are returned by term( ) and applies addition or subtraction to them. If the element( ) method encounters parentheses, it makes a call to sum( ) to handle the nested expression. Eventually, the nested sum returns (possibly after further recursion), and the parenthesized expression is reduced to a single value, which is returned by element( ). The magic of recursion has untangled the nesting for us. The other small piece of magic here is in the ordering of the three parser methods. Having sum( ) call term( ) and term( ) call element( ) imposes the precedence of operators; i.e., "atomic" values are parsed first (at the bottom), then multiplication, and finally, addition or subtraction. The grammar parsing relies on four simple helper methods that make the code more manageable: token( ), consume( ), match( ), and more( ). token( ) calls the string tokenizer to get the next value, and match( ) compares it with a specified value. consume( ) is used to move to the next token, and more( ) indicates when the final token has been processed. 18.3.4. Printing JTablesJava 5.0 introduced an API that makes it easy to print JTables. It is now so easy, in fact, that you might program it accidentally. Think we're kidding? If you accept the basic default behavior, all that is required to pop up a print dialog box and print is the following: myJTable.print( ); That's it. The default behavior scales the printed table to the width of the page. This is called "fit width" mode. You can control that setting using the PrintMode enumeration of JTable, which has values of NORMAL and FIT_WIDTH: table.print( JTable.PrintMode.NORMAL ); The "normal" (ironically, nondefault) mode will allow the table to split across multiple pages horizontally to print without sizing down. In both cases, the table rows may span multiple pages vertically. Other forms of the JTable print( ) method allow you to add header and footer text to the page and to take greater control of the printing process and attributes. We'll talk a little more about printing when we cover 2D drawing in Chapter 20. |