Home > Articles > Programming > Java

  • Print
  • + Share This
Like this article? We recommend

Like this article? We recommend

Playing with Columns

When a table component is first displayed, all columns are given the same width and automatically fill a table component's entire width. All column widths change appropriately as a user resizes the window containing a table component. A user can also resize a column by moving the mouse pointer over the narrow separator line that appears on either side of the column's header cell. (The mouse pointer's shape changes to a left-right arrow shape to indicate that resizing is in effect.) The user then presses the left mouse button and drags the mouse (in an appropriate direction) to resize the column. Figure 4 illustrates a table component with all columns having the same width just before the user decides to change a column's width.

Figure 4 The user has the option to resize column E or column F.

When a column is resized, other column widths must change so that a table component's width remains the same. JTable provides several ways to accomplish that task. By default, the widths of all columns that are to the right of the column being resized (assuming that the mouse is being dragged to the right) have their widths adjusted so that the overall table component width remains the same. (The widths of columns to the left of the column being resized are not affected unless the mouse is being dragged to the left, in which case only the column immediately to the left of the column being resized is affected—in addition to the columns to the right.) You can specify the auto resize mode for a table component by calling JTable's setAutoResizeMode(int mode) method with one of JTable's auto resize constants described in Table 4.

Table 4 JTable Auto Resize Constants

Constant

Description

AUTO_RESIZE_ALL_COLUMNS

Proportionally adjusts all column widths during a resize operation.

AUTO_RESIZE_LAST_COLUMN

Adjusts only the last column's width during a resize operation.

AUTO_RESIZE_NEXT_COLUMN

Adjusts only the width of the column to the right (or left, depending on the direction that the mouse is dragged) of the column being resized.

AUTO_RESIZE_OFF

Does not automatically adjust column widths. Displays a horizontal scrollbar instead.

AUTO_RESIZE_SUBSEQUENT_COLUMNS

Proportionally adjusts the widths of all columns to the right of the column being resized (and possibly the column immediately to the left, depending on the direction that the mouse is dragged). That is the default behavior.


To experiment with column resizing, compile Listing 4's source code to the TableDemo4 application and run the resulting program.

Listing 4: TableDemo4.java

// TableDemo4.java

import java.awt.*;
import java.awt.event.*;

import javax.swing.*;
import javax.swing.table.DefaultTableModel;

class TableDemo4 extends JFrame implements ActionListener
{
  JTable jt;

  TableDemo4 (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 table with a default table model that specifies 10
   // rows by 10 columns dimensions.

   jt = new JTable (new DefaultTableModel (10, 10));

   // Assign column identifiers (headers) to the columns.

   String [] columnIDs =
   {
     "A", "B", "C", "D", "E", "F", "G", "H", "I", "J"
   };

   ((DefaultTableModel) 
   jt.getModel ()).setColumnIdentifiers (columnIDs);

   // 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. It also allows the table's column headers to be
   // displayed.

   getContentPane ().add (jsp);

   // Create a panel for positioning buttons.

   JPanel jp = new JPanel ();

   // Create an "All Columns" button, register the current TableDemo4
   // object as a listener to that button's action events, and add
   // that button to the panel.

   JButton jb = new JButton ("All Columns");
   jb.addActionListener (this);
   jp.add (jb);

   // Create a "Last Column" button, register the current TableDemo4
   // object as a listener to that button's action events, and add
   // that button to the panel.

   jb = new JButton ("Last Column");
   jb.addActionListener (this);
   jp.add (jb);

   // Create a "Next Column" button, register the current TableDemo4
   // object as a listener to that button's action events, and add
   // that button to the panel.

   jb = new JButton ("Next Column");
   jb.addActionListener (this);
   jp.add (jb);

   // Create an "Off" button, register the current TableDemo4 object
   // as a listener to that button's action events, and add that
   // button to the panel.

   jb = new JButton ("Off");
   jb.addActionListener (this);
   jp.add (jb);

   // Create a "Subsequent Columns" button, register the current
   // TableDemo4 object as a listener to that button's action
   // events, and add that button to the panel.

   jb = new JButton ("Subsequent Columns");
   jb.addActionListener (this);
   jp.add (jb);

   // Add the panel to the south portion of the frame window's
   // content pane.

   getContentPane ().add (jp, BorderLayout.SOUTH);

   // Establish the frame's initial size as 600x250 pixels.

   setSize (600, 250);

   // Display the frame window and all contained components.

   setVisible (true);
  }

  public void actionPerformed (ActionEvent e)
  {
   // Identify the button that initiated the event.

   JButton jb = (JButton) e.getSource ();

   // Obtain the button's label.

   String label = jb.getText ();

   // Select appropriate resize mode.

   if (label.equals ("All Columns"))
     jt.setAutoResizeMode (JTable.AUTO_RESIZE_ALL_COLUMNS);
   else
   if (label.equals ("Last Column"))
     jt.setAutoResizeMode (JTable.AUTO_RESIZE_LAST_COLUMN);
   else
   if (label.equals ("Next Column"))
     jt.setAutoResizeMode (JTable.AUTO_RESIZE_NEXT_COLUMN);
   else
   if (label.equals ("Off"))
     jt.setAutoResizeMode (JTable.AUTO_RESIZE_OFF);
   else
     jt.setAutoResizeMode (JTable.AUTO_RESIZE_SUBSEQUENT_COLUMNS);
  }

  public static void main (String [] args)
  {
   // Create a TableDemo4 object, which creates the GUI.

   new TableDemo4 ("Table Demo #4");
  }
}

In addition to setAutoResizeMode(int mode), JTable declares a getAutoResizeMode() method that you can call to obtain the current auto resize mode. Also, JTable declares a doLayout() method that a container's layout manager calls to lay out all columns in a table component. The doLayout() method uses the current auto resize mode to help it determine how to size columns.

If you position the mouse pointer over a column's header cell and press the left mouse button, you can drag that column to another location in the table component. You can also accomplish that task programmatically by calling JTable's moveColumn(int columnIndex, int newColumnIndex) method. Figure 5 demonstrates the use of moveColumn(int columnIndex, int newColumnIndex) to swap the leftmost and next-to-leftmost columns.

Figure 5 The leftmost and next-to-leftmost columns are swapped by calling jt.moveColumn (0, 1); (assuming that jt references a JTable object).

To examine the source code to Figure 5's TableDemo5 application, check out Listing 5.

Listing 5: TableDemo5.java

// TableDemo5.java

import java.awt.*;
import java.awt.event.*;

import javax.swing.*;
import javax.swing.table.DefaultTableModel;

class TableDemo5 extends JFrame implements ActionListener
{
  JTable jt;

  TableDemo5 (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 default table model consisting of 4 rows by 2 
   // columns.

   DefaultTableModel dtm = new DefaultTableModel (4, 2);

   // Assign column identifiers (headers) to the columns.

   String [] columnTitles =
   {
     "Name",
     "Address",
   };

   dtm.setColumnIdentifiers (columnTitles);

   // Populate all cells in the default table model.

   String [] names =
   {
     "John Doe",
     "Jane Smith",
     "Jack Jones",
     "Paul Finch"
   };

   String [] addresses =
   {
     "200 Fox Street",
     "Apt. 555",
     "Box 9000",
     "1888 Apple Avenue"
   };

   int nrows = dtm.getRowCount ();

   for (int i = 0; i < nrows; i++)
   {
      dtm.setValueAt (names [i], i, 0);
      dtm.setValueAt (addresses [i], i, 1);
   }

   // Create a table using the previously created default table
   // model.

   jt = new JTable (dtm);

   // 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);

   // Create a panel for positioning buttons.

   JPanel jp = new JPanel ();

   // Create a "Swap" button, register the current TableDemo8 object
   // as a listener to that button's action events, and add that
   // button to the panel.

   JButton jb = new JButton ("Swap");
   jb.addActionListener (this);
   jp.add (jb);

   // Add the panel to the south portion of the frame window's
   // content pane.

   getContentPane ().add (jp, BorderLayout.SOUTH);

   // Establish the overall size of the frame window to 400
   // horizontal pixels by 150 vertical pixels.

   setSize (400, 150);

   // Display the frame window and all contained
   // components/containers.

   setVisible (true);
  }

  public void actionPerformed (ActionEvent e)
  {
   // Swap columns 0 and 1.

   jt.moveColumn (0, 1);
  }

  public static void main (String [] args)
  {
   // Create a TableDemo5 object, which creates the GUI.

   new TableDemo5 ("Table Demo #5");
  }
}

Column Models

If you were to examine the source code to JTable's moveColumn(int columnIndex, int newColumnIndex) method, you would find the following method call: getColumnModel ().moveColumn (columnIndex, newColumnIndex). (I've changed the names of the arguments, to be consistent with my choices of argument names.) That method call suggests something called a column model.

In addition to a model, a table component contains a column model. The column model manages each column of cells that a UI delegate displays. Column models are created from classes that directly or indirectly, by way of a superclass, implement the TableColumnModel interface. JTable provides a setColumnModel(TableColumnModel m) method that its constructors call to establish the column model. JTable also provides a getColumnModel() method that returns a TableColumnModel reference to the current column model. To properly implement TableColumnModel, classes provide implementations for those methods described in Table 5.

Table 5 TableColumnModel Methods

Method

Description

addColumn(TableColumn tc)

Appends the TableColumn object referenced by tc to the end of an array of TableColumn objects. Also, calls all listeners' columnAdded(TableColumnModelEvent e) methods.

addColumnModelListener(TableColumnModelListener l)

Adds the listener referenced by l to the column model's array of listeners. When a change is made to the column model, those listeners are notified.

getColumn(int columnIndex)

Returns a reference to the TableColumn object located at columnIndex.

getColumnCount()

Returns an integer that contains the number of columns managed by the column model.

getColumnIndex(Object columnID)

Returns an integer that contains the index of the first column whose column identifier matches columnID.

getColumnIndexAtX(int xPosition)

Returns an integer that contains the index of the column at xPosition or -1 if no column is located at xPosition.

getColumnMargin()

Returns an integer that contains the number of pixels between cells in a column.

getColumns()

Returns an Enumeration of all TableColumn objects managed by the column model.

getColumnSelectionAllowed()

Returns a Boolean true value if columns can be selected.

getSelectedColumnCount()

Returns an integer that identifies the number of selected columns—0, if no columns have been selected.

getSelectedColumns()

Returns an integer array of column indexes for all selected columns. The array has 0 length if no columns have been selected.

getSelectionModel()

Returns a reference to a ListSelectionModel object that maintains the table component's selection state.

getTotalColumnWidth()

Returns an integer containing the total width (in pixels) of all columns.

moveColumn(int columnIndex, int newIndex)

Moves the column (and its header cell) from columnIndex to newIndex. Also, calls all listeners' columnMoved(TableColumnModelEvent e) methods.

removeColumn(TableColumn tc)

Removes the TableColumn object referenced by tc from the array of TableColumn objects. Also, calls all listeners' columnRemoved(TableColumnModelEvent e) methods.

removeColumnModelListener(TableColumnModelListener l)

Removes the listener referenced by l from the column model's array of listeners.

setColumnMargin(int newMargin)

Sets all TableColumn margins to newMargin pixels. Also, calls all listeners' columnMarginChanged(ChangeEvent e) methods.

setColumnSelectionAllowed(boolean isSelect)

Allows columns to be selected if isSelect is true.

setSelectionModel(ListSelectionModel m)

Sets the column's selection model to the object referenced by m.


Unlike data models, you don't normally create your own column models. Instead, JTable creates a column model on your behalf. It creates that column model from the DefaultTableColumnModel class (which implements the TableColumnModel interface).

TableColumnModel's methods are called by your programs, by various parts of the table component, or by both. As you can see, some of the methods refer to the TableColumn class. That class gives you the ability to customize individual columns. For example, you can determine the appearance of some or all cells in a column by specifying a renderer for that column. (You will learn how to do that a bit later in this article.)

One important capability that TableColumnModel provides you with is column model listener registration. You can register a listener with the column model to respond to various events by calling the addColumnModelListener(TableColumnModelListener l) method. When certain column model methods are called, various methods declared by your listener will be called in response. For example, when a column model's moveColumn(int columnIndex, int newIndex) method is called, each listener's columnMoved(TableColumnModelEvent e) method is called by the column model to alert that listener to the fact that a column has moved.

Enough theory! Listing 6 presents source code to the TableDemo6 application. That source code demonstrates the creation of TableColumn objects, adding those objects to the column model, removing TableColumn objects from the model, changing column margins, registering a column model listener, and listening to most of the column model events.

Listing 6: TableDemo6.java

// TableDemo6.java

import java.awt.*;
import java.awt.event.*;

import javax.swing.*;
import javax.swing.event.*;
import javax.swing.table.*;

class TableDemo6 extends JFrame implements ActionListener,
                      TableColumnModelListener
{
  JTable jt;

  TableDemo6 (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 default table model consisting of 4 rows by 2 
   // columns.

   DefaultTableModel dtm = new DefaultTableModel (4, 2);

   // Assign column identifiers (headers) to the columns.

   String [] columnTitles =
   {
     "Name",
     "Address",
   };

   dtm.setColumnIdentifiers (columnTitles);

   // Populate all cells in the default table model.

   String [] names =
   {
     "John Doe",
     "Jane Smith",
     "Jack Jones",
     "Paul Finch"
   };

   String [] addresses =
   {
     "200 Fox Street",
     "Apt. 555",
     "Box 9000",
     "1888 Apple Avenue"
   };

   int nrows = dtm.getRowCount ();

   for (int i = 0; i < nrows; i++)
   {
      dtm.setValueAt (names [i], i, 0);
      dtm.setValueAt (addresses [i], i, 1);
   }

   // Create a table using the previously created default table
   // model.

   jt = new JTable (dtm);

   // Register the current TableDemo6 object as a listener for table
   // column model events.

   jt.getColumnModel ().addColumnModelListener (this);

   // 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);

   // Create a panel for positioning buttons.

   JPanel jp = new JPanel ();

   // Create an "Add" button, register the current TableDemo6 object
   // as a listener to that button's action events, and add that
   // button to the panel.

   JButton jb = new JButton ("Add");
   jb.addActionListener (this);
   jp.add (jb);

   // Create a "Remove" button, register the current TableDemo6
   // object as a listener to that button's action events, and add
   // that button to the panel.

   jb = new JButton ("Remove");
   jb.addActionListener (this);
   jp.add (jb);

   // Create a "Change Margin" button, register the current
   // TableDemo6 object as a listener to that button's action
   // events, and add that button to the panel.

   jb = new JButton ("Change Margin");
   jb.addActionListener (this);
   jp.add (jb);

   // Add the panel to the south portion of the frame window's
   // content pane.

   getContentPane ().add (jp, BorderLayout.SOUTH);

   // Establish the overall size of the frame window to 400
   // horizontal pixels by 175 vertical pixels.

   setSize (400, 175);

   // Display the frame window and all contained
   // components/containers.

   setVisible (true);
  }

  public void actionPerformed (ActionEvent e)
  {
   // Identify the button that initiated the event.

   JButton jb = (JButton) e.getSource ();

   // Obtain the button's label.

   String label = jb.getText ();

   if (label.equals ("Add"))
   {
     // Create a new column.

     TableColumn tc = new TableColumn ();

     // Set the column's header to Extra.

     tc.setHeaderValue ("Extra");

     // Add the column to the end of the columns managed by the
     // column model.

     jt.addColumn (tc);
   }
   else
   if (label.equals ("Remove"))
   {
     // If there is at least one column ...

     if (jt.getColumnModel ().getColumnCount () != 0)
     {
       // Retrieve leftmost column.

       TableColumn tc = jt.getColumnModel ().getColumn (0);

       // Remove that column.

       jt.removeColumn (tc);
     }
   }
   else
   {
     // Get the column model.

     TableColumnModel tcm = jt.getColumnModel ();

     // Change the margin that surrounds a column's cell values
     // and the grid lines.

     tcm.setColumnMargin ((int) (Math.random () * 30));
   }
  }

  public void columnAdded (TableColumnModelEvent e)
  {
   System.out.println ("Column added");
  }

  public void columnMarginChanged (ChangeEvent e)
  {
   System.out.println ("Column margin changed");
  }

  public void columnMoved (TableColumnModelEvent e)
  {
   // Not needed (but must implement).
  }

  public void columnRemoved (TableColumnModelEvent e)
  {
   System.out.println ("Column removed");
  }

  public void columnSelectionChanged (ListSelectionEvent e)
  {
   System.out.println ("Selection changed");
  }

  public static void main (String [] args)
  {
   // Create a TableDemo6 object, which creates the GUI.

   new TableDemo6 ("Table Demo #6");
  }
}

Compile the TableDemo6 source code and run the resulting program. Press the Add button, and you should notice the addition of an extra column, as Figure 6 illustrates.

Figure 6 Clicking the Add button results in a new column (and a surprise).

There is something strange about Figure 6. Notice that the new column's cell values duplicate the leftmost column's cell values? How did that happen? The answer is actually quite simple.

As you probably know by now, you can drag a table component's columns with the mouse. Somehow, the column's cell values accompany the column to its new position. To make that happen, the TableColumn class includes a protected modelIndex field that links the column in the column model to the column of cells stored in the model. That modelIndex field is initialized during the creation of the TableColumn object and remains the same (unless you call TableColumn's setModelIndex(int modelIndex) method) throughout the life of the TableColumn object. Just before a cell is rendered, JTable's prepareRenderer(TableCellRenderer renderer, int rowIndex, int columnIndex) method calls JTable's getValueAt(int rowIndex, int columnIndex) method. That method executes return getModel().getValueAt(rowIndex, convertColumnIndexToModel(columnIndex)); to retrieve the value of the cell about to be rendered. If you look at JTable's convertColumnIndexToModel(int viewColumnIndex) method, you will find the following code fragment: return getColumnModel().getColumn(viewColumnIndex).getModelIndex();. As you can see, the value of the TableColumn's modelIndex field is retrieved. If you could see that return value, you would notice that it is 0. Basically, the leftmost and the new rightmost column share the same model index.

How is it possible that both the leftmost and rightmost columns share the same modelIndex? The answer lies in the TableColumn() constructor. That constructor assigns 0 to modelIndex. And that value was also used to identify the leftmost column in the model when the JTable object was created.

NOTE

TableDemo6 calls JTable's addColumn(TableColumn tc) and removeColumn(TableColumn tc) methods to add and remove columns. If you were to look at the source code for those methods, you would discover that they call getColumnModel() followed by calls to the column model's addColumn(TableColumn tc) and removeColumn(TableColumn tc) methods. In a sense, you can think of JTable's addColumn(TableColumn tc), removeColumn(TableColumn tc), and getValueAt(rowIndex, columnIndex) methods as convenience methods that wrap themselves around calls to equivalent methods in the table component's model and column model. Apart from removeColumn(TableColumn tc) (which is a convenience method), the other two methods perform various tasks behind the scenes. They are more than just convenience methods. Understanding that will help you realize why methods are duplicated in different places.

  • + Share This
  • 🔖 Save To Your Account