Tables 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.
JTable 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.javaimportjava.awt.*;importjava.awt.event.*;importjavax.swing.*;importjavax.swing.table.*;publicclassDullShipTable{publicstaticvoidmain(String[]args){// create some tabular dataString[]headings=newString[]{"Number","Hot?","Origin","Destination","Ship Date","Weight"};Object[][]data=newObject[][]{{"100420",Boolean.FALSE,"Des Moines IA","Spokane WA","02/06/2000",newFloat(450)},{"202174",Boolean.TRUE,"Basking Ridge NJ","Princeton NJ","05/20/2000",newFloat(1250)},{"450877",Boolean.TRUE,"St. Paul MN","Austin TX","03/20/2000",newFloat(1745)},{"101891",Boolean.FALSE,"Boston MA","Albany NY","04/04/2000",newFloat(88)}};// create the data model and the JTableJTabletable=newJTable(data,headings);JFrameframe=newJFrame("DullShipTable v1.0");frame.add(newJScrollPane(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.
For very little typing, we’ve gotten some pretty impressive stuff. Here are a few things that come for free:
The JTable has
automatically formatted the column headings differently than the
table cells. It’s clear that they are not part of the table’s data
area.
If a cell’s data is too long to fit in the cell, it is automatically truncated and shown with an ellipsis (...). This is shown in the Origin cell in the second row in Figure 18-7.
You can click on any cell in the table to select its entire
row. This behavior is controllable; you can select single cells,
entire rows, entire columns, or some combination of these. To
configure the JTable’s
selection behavior, use the setCellSelectionEnabled(), setColumnSelectionAllowed(), and
setRowSelectionAllowed() methods.
Double-clicking on a cell opens it for editing; you’ll get a little cursor in the cell. You can type directly into the cell to change the cell’s data.
If you position the mouse cursor between two column
headings, you’ll get a little left-right arrow cursor. Click and
drag to change the size of the column to the left. Depending on
how the JTable is configured,
the other columns may also change size. The resizing behavior is
controlled with the setAutoResizeMode() method.
If you click and drag on a column heading, you can move the entire column to another part of the table.
JTable 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:
public int getRowCount(),
public int
getColumnCount()Returns the number of rows and columns in this data model
public Object
getValueAt(int row , int column
)Returns the value for the given cell
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:
publicstaticclassShipTableModelextendsAbstractTableModel{privateObject[][]data=newObject[][]{{"100420",Boolean.FALSE,"Des Moines IA","Spokane WA","02/06/2000",newFloat(450)},{"202174",Boolean.TRUE,"Basking Ridge NJ","Princeton NJ","05/20/2000",newFloat(1250)},{"450877",Boolean.TRUE,"St. Paul MN","Austin TX","03/20/2000",newFloat(1745)},{"101891",Boolean.FALSE,"Boston MA","Albany NY","04/04/2000",newFloat(88)}};publicintgetRowCount(){returndata.length;}publicintgetColumnCount(){returndata[0].length;}publicObjectgetValueAt(introw,intcolumn){returndata[row][column];}}
We’d like to use the same column headings that 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:
privateString[]headings=newString[]{"Number","Hot?","Origin","Destination","Ship Date","Weight"};publicStringgetColumnName(intcolumn){returnheadings[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:
publicClassgetColumnClass(intcolumn){returndata[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.javaimportjava.awt.*;importjava.awt.event.*;importjavax.swing.*;importjavax.swing.table.*;publicclassShipTable{publicstaticclassShipTableModelextendsAbstractTableModel{privateString[]headings=newString[]{"Number","Hot?","Origin","Destination","Ship Date","Weight"};privateObject[][]data=newObject[][]{{"100420",Boolean.FALSE,"Des Moines IA","Spokane WA","02/06/2000",newFloat(450)},{"202174",Boolean.TRUE,"Basking Ridge NJ","Princeton NJ","05/20/2000",newFloat(1250)},{"450877",Boolean.TRUE,"St. Paul MN","Austin TX","03/20/2000",newFloat(1745)},{"101891",Boolean.FALSE,"Boston MA","Albany NY","04/04/2000",newFloat(88)}};publicintgetRowCount(){returndata.length;}publicintgetColumnCount(){returndata[0].length;}publicObjectgetValueAt(introw,intcolumn){returndata[row][column];}publicStringgetColumnName(intcolumn){returnheadings[column];}publicClassgetColumnClass(intcolumn){returndata[0][column].getClass();}}publicstaticvoidmain(String[]args){// create the data model and the JTableTableModelmodel=newShipTableModel();JTabletable=newJTable(model);table.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);JFrameframe=newJFrame("ShipTable v1.0");frame.getContentPane().add(newJScrollPane(table));frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);frame.setSize(500,200);frame.setVisible(true);}}
The running application is shown in Figure 18-8.
To 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.
Our spreadsheet does the expected stuff—allowing you to enter
numbers or mathematical expressions such as (A1*B2)+C3 into each cell.[41] 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.javaimportjava.util.StringTokenizer;importjavax.swing.*;importjavax.swing.table.AbstractTableModel;importjava.awt.event.*;publicclassSpreadsheetModelextendsAbstractTableModel{Expression[][]data;publicSpreadsheetModel(introws,intcols){data=newExpression[rows][cols];}publicvoidsetValueAt(Objectvalue,introw,intcol){data[row][col]=newExpression((String)value);fireTableDataChanged();}publicObjectgetValueAt(introw,intcol){if(data[row][col]!=null)try{returndata[row][col].eval()+"";}catch(BadExpressione){return"Error";}return"";}publicintgetRowCount(){returndata.length;}publicintgetColumnCount(){returndata[0].length;}publicbooleanisCellEditable(introw,intcol){returntrue;}classExpression{Stringtext;StringTokenizertokens;Stringtoken;Expression(Stringtext){this.text=text.trim();}floateval()throwsBadExpression{tokens=newStringTokenizer(text," */+-()",true);try{returnsum();}catch(Exceptione){thrownewBadExpression();}}privatefloatsum(){floatvalue=term();while(more()&&match("+-"))if(match("+")){consume();value=value+term();}else{consume();value=value-term();}returnvalue;}privatefloatterm(){floatvalue=element();while(more()&&match("*/"))if(match("*")){consume();value=value*element();}else{consume();value=value/element();}returnvalue;}privatefloatelement(){floatvalue;if(match("(")){consume();value=sum();}else{Stringsvalue;if(Character.isLetter(token().charAt(0))){intcol=findColumn(token().charAt(0)+"");introw=Character.digit(token().charAt(1),10);svalue=(String)getValueAt(row,col);}elsesvalue=token();value=Float.parseFloat(svalue);}consume();// ")" or value tokenreturnvalue;}privateStringtoken(){if(token==null)while((token=tokens.nextToken()).equals(" "));returntoken;}privatevoidconsume(){token=null;}privatebooleanmatch(Strings){returns.indexOf(token())!=-1;}privatebooleanmore(){returntokens.hasMoreTokens();}}classBadExpressionextendsException{}publicstaticvoidmain(String[]args){JFrameframe=newJFrame("Excelsior!");JTabletable=newJTable(newSpreadsheetModel(15,5));table.setPreferredScrollableViewportSize(table.getPreferredSize());table.setCellSelectionEnabled(true);frame.getContentPane().add(newJScrollPane(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() in
order 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 names (e.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;
that is, “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.
Java 6 introduced easy-to-use sorting and filtering for
JTables. The following
example demonstrates use of the default TableRowSorter and a simple regular expression
filter.
//file: SortFilterTable.javaimportjavax.swing.*;importjavax.swing.table.*;importjavax.swing.event.*;importjava.awt.BorderLayout;importjava.util.regex.PatternSyntaxException;publicclassSortFilterTableextendsJFrame{privateJTabletable;privateJTextFieldfilterField;publicSortFilterTable(){super("Table Sorting & Filtering");setSize(500,200);setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);// Create a simple table modelTableModelmodel=newAbstractTableModel(){privateString[]columns={"Name","Pet","Children"};privateObject[][]people={{"Dan Leuck","chameleon",1},{"Pat Niemeyer","sugar glider",2},{"John Doe","dog",3},{"Jane Doe","panda",2}};publicintgetColumnCount(){returncolumns.length;}publicintgetRowCount(){returnpeople.length;}publicObjectgetValueAt(introw,intcol){returnpeople[row][col];}publicClassgetColumnClass(intcol){returngetValueAt(0,col).getClass();}};table=newJTable(model);table.setAutoCreateRowSorter(true);table.setFillsViewportHeight(true);// Create the filter areaJPanelfilterPanel=newJPanel(newBorderLayout());JLabelfilterLabel=newJLabel("Filter ",SwingConstants.TRAILING);filterPanel.add(filterLabel,BorderLayout.WEST);filterField=newJTextField();filterLabel.setLabelFor(filterField);filterPanel.add(filterField);// Apply the filter when the filter text field changesfilterField.getDocument().addDocumentListener(newDocumentListener(){publicvoidchangedUpdate(DocumentEvente){filter();}publicvoidinsertUpdate(DocumentEvente){filter();}publicvoidremoveUpdate(DocumentEvente){filter();}});filterPanel.setBorder(BorderFactory.createEmptyBorder(2,2,2,2));add(filterPanel,BorderLayout.NORTH);add(newJScrollPane(table));}// Filter on the first columnprivatevoidfilter(){RowFilter<TableModel,Object>filter=null;// Update if the filter expression is validtry{// Apply the regular expression to columns 0 and 1filter=RowFilter.regexFilter(filterField.getText(),0,1);}catch(PatternSyntaxExceptione){return;}((TableRowSorter)table.getRowSorter()).setRowFilter(filter);}publicstaticvoidmain(String[]args){newSortFilterTable().setVisible(true);}}
Try clicking on the column headers to sort. We are using the
default sorting behavior, which utilizes the natural sort order of cell
values (i.e., alphabetical for strings, value for numbers, etc.). You
can easily override the sorting behavior by implementing your own
comparator and setting it on the TableRowSorter:
TableRowSorter<TableModel>reverseSorter=newTableRowSorter<TableModel>(table.getModel());reverseSorter.setComparator(0,newComparator<String>(){publicintcompare(Stringa,Stringb){return-a.compareTo(b);}});table.setRowSorter(reverseSorter);
If you require more advanced sorting, you can subclass TableRowSorter or its
superclass, DefaultRowSorter.
Entering text in the field above the table will apply a filter using the text as a regular expression over the values in the first two columns (indices 0 and 1). For example, try entering “Doe”. The table will now display only John Doe and Jane Doe.
Swing makes the printing of JTables a snap. Think we’re kidding? If you accept the basic default behavior, all that is required to pop up a print dialog box is the following:
myJTable.();
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.(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.