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. If you go with the default options, however, 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 two-dimensional 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 a JFrame to hold the table
    JFrame f = new JFrame("DullShipTable v1.0");
    f.addWindowListener(new WindowAdapter( ) {
      public void windowClosing(WindowEvent e) { System.exit(0); }
    });
    f.setSize(500, 200);
    f.setLocation(200, 200);
    
    // create the data model and the JTable
    JTable table = new JTable(data, headings);
    
    // put it all together
    f.getContentPane( ).add(new JScrollPane(table));
    f.setVisible(true);
  }
}

This small application produces the display shown in Figure 15.7.

A rudimentary JTable

Figure 15-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 ellipses (...). This is shown in the “Origin” cell in the first two rows in Figure 15.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 set-RowSelectionAllowed( ) 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 ( )

These methods return the number of rows and columns in this data model.

public Object getValueAt (int row , int column )

This method 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 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 non-editable, 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 show up 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. The running application is shown in Figure 15.8.

//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 a JFrame to hold the table
    JFrame f = new JFrame("ShipTable v1.0");
    f.addWindowListener(new WindowAdapter( ) {
      public void windowClosing(WindowEvent e) { System.exit(0); }
    });
    f.setSize(500, 200);
    f.setLocation(200, 200);
    
    // create the data model and the JTable
    TableModel model = new ShipTableModel( );
    JTable table = new JTable(model);
    
    table.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
    
    // put it all together
    f.getContentPane( ).add(new JScrollPane(table));
    f.setVisible(true);
  }
}
Customizing a table

Figure 15-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 15.9) using almost no customization of the JTable. All of the data processing is in a TableModel called SpreadSheetModel.

Our spreadsheet will do the expected stuff—allowing you to enter numbers or mathematical expression like (A1*B2)+C3 into each cell. All of the 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 will take us only about fifty lines of code to implement a parser capable of handling basic arithmetic with arbitrarily nested parentheses.[44]

A simple spreadsheet

Figure 15-9. A simple spreadsheet

Here is 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.valueOf( svalue ).floatValue( );;
      }
      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!");
    frame.addWindowListener(new WindowAdapter( ) {
      public void windowClosing(WindowEvent we) { System.exit(0); }
    });
    JTable table = new JTable( new SpreadsheetModel(15, 5) );
    table.setPreferredScrollableViewportSize(
        table.getPreferredSize( ) );
    table.setCellSelectionEnabled(true);
    frame.getContentPane( ).add( new JScrollPane( table ) );
    frame.pack(); frame.show( );
  }
}

Our model extends AbstractTableModel and overrides just a few methods. As you can see, our data is stored in a two-dimensional 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 that 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!

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 will then be processed by the three parser methods: sum( ), term( ), and element( ). The methods call one another generally in that order (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 will return (possibly after further recursion) and the parenthesized expression will have been 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 multiplications happen, and finally addition or subtraction of terms is applied.

The grammar parsing relies on four simple helper methods; token( ), consume( ), match( ), and more( ) make the code more manageable. 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.



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

Get Learning Java 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.