Tables

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.

A First Stab: Freeloading

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.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.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.

A rudimentary JTable

Figure 18-7. A rudimentary JTable

For very little typing, we’ve gotten some pretty impressive stuff. Here are a few things that come for free:

Column headings

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.

Cell overflow

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.

Row selection

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.

Cell editing

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.

Column sizing

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.

Column reordering

If you click and drag on a column heading, you can move the entire column to another part of the table.

Play with this for a while. It’s fun!

Round Two: Creating a Table Model

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:

    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 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:

    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.

Customizing a table

Figure 18-8. Customizing a table

Round Three: A Simple Spreadsheet

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.

A simple spreadsheet

Figure 18-9. A simple spreadsheet

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.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() 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.

Sorting and Filtering

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.java
    import javax.swing.*;
    import javax.swing.table.*;
    import javax.swing.event.*;
    
    import java.awt.BorderLayout;
    import java.util.regex.PatternSyntaxException;
    
    public class SortFilterTable extends JFrame {
    
        private JTable table;
        private JTextField filterField;
    
        public SortFilterTable() {
            
            super("Table Sorting & Filtering");
            setSize(500, 200);
            setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
    
            // Create a simple table model
            TableModel model = new AbstractTableModel() {
                private String[] columns = {"Name", "Pet", "Children"};
                
                private Object[][] people = {
                        {"Dan Leuck", "chameleon", 1},
                        {"Pat Niemeyer", "sugar glider", 2},
                        {"John Doe", "dog", 3},
                        {"Jane Doe", "panda", 2}
                        };            
                
                public int getColumnCount() { return columns.length; }
    
                public int getRowCount() { return people.length; }
    
                public Object getValueAt(int row, int col) { 
                    return people[row][col]; 
                }

                public Class getColumnClass(int col) {
                    return getValueAt(0, col).getClass();
                }

            };
            
            table = new JTable(model);
            table.setAutoCreateRowSorter(true);
            table.setFillsViewportHeight(true);
            
            // Create the filter area
            JPanel filterPanel = new JPanel(new BorderLayout());
            JLabel filterLabel = new JLabel("Filter ", 
                SwingConstants.TRAILING);
            filterPanel.add(filterLabel, BorderLayout.WEST);
            filterField = new JTextField();
            filterLabel.setLabelFor(filterField);
            filterPanel.add(filterField);
            
            // Apply the filter when the filter text field changes
            filterField.getDocument().addDocumentListener(
                new DocumentListener() {
                    public void changedUpdate(DocumentEvent e) {
                        filter();
                    }
                    public void insertUpdate(DocumentEvent e) {
                        filter();
                    }
                    public void removeUpdate(DocumentEvent e) {
                        filter();
                    }
                });
            
            filterPanel.setBorder(BorderFactory.createEmptyBorder(2, 
                2, 2, 2));
    
            add(filterPanel, BorderLayout.NORTH);
    
            add(new JScrollPane(table));
        }
    
        // Filter on the first column
        private void filter() {
            RowFilter<TableModel, Object> filter = null;
            
            // Update if the filter expression is valid
            try {
                // Apply the regular expression to columns 0 and 1
                filter = RowFilter.regexFilter(filterField.getText(),
                    0, 1);
            } catch (PatternSyntaxException e) {
                return;
            }
            ((TableRowSorter)table.getRowSorter()).setRowFilter(
                filter);
        }
    
        public static void main(String[] args) {
            new SortFilterTable().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 
        = new TableRowSorter<TableModel>(table.getModel()); 
    reverseSorter.setComparator(0, new Comparator<String>() {
        public int compare(String a, String b) {
            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.

Printing JTables

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.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.



[41] You may need to double-click on a cell to edit it.

Get Learning Java, 4th Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.