Home > Articles > Programming > Java

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

Like this article? We recommend

Selecting Cells

Being able to select one or more cells in a table component is an important task. Once appropriate cells have been selected, you can do anything that you want with the values in those cells. For example, you could write code that either copies or cuts the values in selected cells to a clipboard, or paste cell values that are already on the clipboard to selected cells. Undoubtedly, you will think of something to do with selected cells and their values.

The table component permits you to select a single row of cells, a single column of cells, or a single cell. That happens when you call JTable's setSelectionMode(int mode) method, where mode contains ListSelectionModel.SINGLE_SELECTION. (You will learn about that method and constant a bit later.) To permit row-based selection, call JTable's setRowSelectionAllowed(boolean isShown) method with true as the value of isShown, and JTable's setColumSelectionAllowed(boolean isShown) method with false as the value of isShown. (When a table component is first created, row-based selection is the default.) However, if you prefer column-based selection, call JTable's setColumnSelectionAllowed(boolean isShown) method with true as the value of isShown, and JTable's setRowSelectionAllowed(boolean isShown) method with false as the value of isShown. Finally, you can permit cell-based selection by calling both methods with true as the value of isShown. At any time, you can query a table component to find out if row-based, column-based, or cell-based selection is in effect by calling JTable's getRowSelectionAllowed() and getColumnSelectionAllowed() methods.

When a row or column of cells is selected, all cells in that row or column, with the single exception of the focused cell, are highlighted in a selection color. The focused cell is not highlighted (apart from a thin border), so it can show the user which cell can receive focus. When the user presses certain keys, the table component starts an editor (which I discuss later) that allows the user to enter a value in the focused cell. To see what it looks like for a row of cells to be selected, and for one of those cells to be the focused cell, examine Figure 8.

Figure 8 When a row is selected, all of its cells (except for the focused cell) appear in a selection color.

For either row or column selection, all cells (except the focused cell) in the selected row or column are highlighted using the current selection foreground and background colors. In Figure 8, the selection foreground color is white (which results in Test being displayed with white pixels), and the selection background color is blue. You set the selection foreground color by calling JTable's setSelectionForeground(Color fg) method; you set the selection background color by calling JTable's setSelectionBackground(Color bg) method. You can query a table component to find out which selection foreground and background colors are being used by calling the getSelectionForeground() and getSelectionBackground() methods, respectively.

How do you find out what row, column, or cell is selected? You can accomplish that task by calling JTable's getSelectedRow() or getSelectedColumn() methods. If row selection is in effect, you will probably call only getSelectedRow() to return the index of the selected row of cells. However, you can also call getSelectedColumn() to identify the focused cell in that row. Similarly, if column selection is in effect, call getSelectedColumn() to return the index of the selected column of cells. You can also call getSelectedRow() to identify the focused cell in that column. Finally, if cell selection is in effect, call both methods to identify the selected and focused cell.

Listing 8 presents source code to a TableDemo8 application. That application allows you to experiment with row selection, column, selection, and cell selection.

Listing 8: TableDemo8.java

// TableDemo8.java

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

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

class TableDemo8 extends JFrame implements ActionListener
{
  JTable jt;

  TableDemo8 (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));

   // Establish blue as the selection foreground color and white as
   // the selection background color.

   jt.setSelectionBackground (Color.blue);
   jt.setSelectionForeground (Color.white);

   // Allow only a single row, a single column, or a single cell to
   // be selected.

   jt.setSelectionMode (ListSelectionModel.SINGLE_SELECTION);

   // Add the table to the center portion of the frame window's
   // content pane.

   getContentPane ().add (jt);

   // Create a panel for positioning buttons.

   JPanel jp = new JPanel ();

   // Create a "Row Selection Only" 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 ("Row Selection Only");
   jb.addActionListener (this);
   jp.add (jb);

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

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

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

   jb = new JButton ("Row and Column Selection");
   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)
  {
   // Print selected row, column, or cell information.

   if (jt.getRowSelectionAllowed () &&
     !jt.getColumnSelectionAllowed ())
   {
     System.out.println ("Selected row = " + 
               jt.getSelectedRow ());

     System.out.println ("Focused cell column in selected row = " 
               + jt.getSelectedColumn () + "\n");
   }
   else
   if (jt.getColumnSelectionAllowed () &&
     !jt.getRowSelectionAllowed ())
   {
     System.out.println ("Selected column = " +
               jt.getSelectedColumn ());

     System.out.println ("Focused cell row in selected column = " 
               + jt.getSelectedRow () + "\n");
   }
   else
   {
     System.out.println ("Selected cell at (row, column) = (" +
               jt.getSelectedRow () + ", " +
               jt.getSelectedColumn () + ")\n");
   }

   // Identify the button that initiated the event.

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

   // Obtain the button's label.

   String label = jb.getText ();

   // Enable row and/or column selection, as appropriate.

   if (label.equals ("Row Selection Only"))
   {
     jt.setRowSelectionAllowed (true);
     jt.setColumnSelectionAllowed (false);
   }
   else
   if (label.equals ("Column Selection Only"))
   {
     jt.setColumnSelectionAllowed (true);
     jt.setRowSelectionAllowed (false);
   }
   else
   {
     jt.setRowSelectionAllowed (true);
     jt.setColumnSelectionAllowed (true);
   }

   // Remove the current selection to prevent confusion.

   jt.clearSelection ();
  }

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

   new TableDemo8 ("Table Demo #8");
  }
}

TableDemo8 presents a GUI consisting of a table component and a panel of three buttons. Those buttons allow you to switch between row selection (which is the default), column selection, and cell selection (that is, row and column selection). Whenever you press a button, index information about selected rows, columns, or individual cells is sent to the standard output device and the selection is cleared (by calling JTable's clearSelection() method). If no row, column, or cell has been selected, -1 returns from getSelectedRow() and getSelectedColumn(), which subsequently prints.

NOTE

When you run TableDemo8, the cell in the upper-left corner is the focused cell and appears to be selected. You can immediately start typing a value into that cell. However, if you press one of the three buttons without clicking the mouse on any cell or using the arrow keys to move around cells, getSelectedRow() and getSelectedColumn() return -1—to indicate no selected cell. Isn't the upper-left cell also selected? The answer is no. When a table component first displays, it needs to identify a default focused cell (which is the cell in the upper-left corner). Because the user did not select that cell, the initial focused cell cannot be regarded as a selected cell. Cells that subsequently receive focus are always considered to be selected.

Selection Models

A table component contains a pair of selection models to manage selected cells. Selection models are created from classes that directly or indirectly, by way of a superclass, implement the ListSelectionModel interface. JTable provides a setSelectionModel(ListSelectionModel m) method that its constructors call to establish the row selection model. JTable also provides a getSelectionModel() method that returns a ListSelectionModel reference to the current row selection model. The column model's TableColumnModel interface provides a setSelectionModel(ListSelectionModel m) method that DefaultTableColumnModel's constructor calls to establish the column selection model. TableColumnModel also provides a getSelectionModel() method that returns a ListSelectionModel reference to the current column selection model. To properly implement ListSelectionModel, classes provide implementations for those methods described in Table 7.

Table 7 ListSelectionModel Methods

Method

Description

addListSelectionListener(ListSelectionListener l)

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

addSelectionInterval(int index0, int index1)

Changes the current selection interval (which is maintained in some kind of data structure) to the union of the current selection interval and the selection interval represented by index0 and index1. Notifies listeners if the change modifies the current selection interval.

clearSelection()

Clears the current selection interval. If the current selection interval was not empty before the clear, notifies listeners of the change.

getAnchorSelectionIndex()

Returns an integer containing the index0 argument from the most recent addSelectionInterval(int index0, int index1), removeSelectionInterval(int index0, int index1), or setSelectionInterval(int index0, int index1) method calls. The return value is known as an anchor index.

getLeadSelectionIndex()

Returns an integer containing the index1 argument from the most recent addSelectionInterval(int index0, int index1), removeSelectionInterval(int index0, int index1), or setSelectionInterval(int index0, int index1) method calls. The return value is known as a lead index.

getMaxSelectionIndex()

Returns an integer containing the last selected index, or -1 if the current selection interval is empty.

getMinSelectionIndex()

Returns an integer containing the first selected index, or -1 if the current selection interval is empty.

getSelectionMode()

Returns an integer containing the current selection mode.

getValueIsAdjusting()

Returns a Boolean containing true if a value is undergoing a series of changes.

insertIndexInterval(int index, int len, boolean bef)

Inserts len entries into the current selection interval before the indexth entry if bef is true or after the indexth entry if bef is false. The idea is to synchronize a selection model with changes made to the table component's model.

isSelectedIndex(int index)

Returns a Boolean containing true if the indexth entry in the current selection interval is selected.

isSelectionEmpty()

Returns a Boolean containing true if the current selection interval reflects no selected entries.

removeIndexInterval(int index0, int index1)

Removes all entries from the current selection interval that range from index0 to index1. The idea is to synchronize a selection model with changes made to the table component's model.

removeListSelectionListener(ListSelectionListener l)

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

removeSelectionInterval(int index0, int index1)

Changes the current selection interval to the set difference of the current selection interval and the selection interval represented by index0 and index1. Notifies listeners if the change modifies the current selection interval.

setAnchorSelectionIndex(int index)

Sets the anchor index to index.

setLeadSelectionIndex(int index)

Sets the lead index to index.

setSelectionInterval(int index0, int index1)

Changes the current selection interval to the selection interval represented by index0 and index1. Notifies listeners if the change modifies the current selection interval.

setSelectionMode(int mode)

Sets the selection mode to either single selection, single interval selection, or multiple interval selection, as specified by the value contained in mode.

setValueIsAdjusting(boolean isAdjusting)

Prevents listeners from being called until a selection change has been finalized, if isAdjusting contains true. That saves listeners from having to respond to intermediate changes in a selection operation, which improves performance. For example, true would be passed, in isAdjusting, to setValueIsAdjusting(boolean isAdjusting) before a drag operation that selects cells, and false would be passed after the drag operation completes.


After working your way through Table 7, you probably have quite a few questions. What is an interval? What is the current selection interval? What is a maximum index? What is a minimum index? What is an anchor index? What is a lead index? What does adjusting mean? Let's see if we can find some answers to those questions.

What is an interval? An interval is a range of integer indexes that identifies a selected region of rows or columns. Each index in that range identifies one selected row or column in the selected region. ListSelectionModel declares three integer constants—SINGLE_SELECTION, SINGLE_INTERVAL_SELECTION, and MULTIPLE_INTERVAL_SELECTION—that identify different kinds of intervals. SINGLE_SELECTION constructs an interval consisting of a single selected row or column. SINGLE_INTERVAL_SELECTION builds on SINGLE_SELECTION by allowing additional rows or columns to be added to a single row or column interval. That happens when you press a Shift key and simultaneously use the mouse or arrow keys to highlight neighboring rows or columns of the single row or column interval. Finally, MULTIPLE_INTERVAL_SELECTION builds on SINGLE_SELECTION and SINGLE_INTERVAL_SELECTION by allowing you to add additional intervals to a single interval. That happens when you press the Ctrl key and simultaneously use the mouse to select a different row or column. You now have a second interval consisting of a single row or column. You can expand that interval to include other rows or columns by releasing Ctrl and pressing Shift while you employ the mouse or arrow keys to highlight neighboring rows or columns. Repeat for as many intervals as desired. Either of the aforementioned constants is passed to JTable's or TableColumnModel's setSelectionMode(int mode) method to establish the selection mode.

What is the current selection interval? The current selection interval is a merging of all selection intervals maintained by a selection model. For example, the current selection interval for the row selection model is a merging of all row selection intervals. Within the current selection interval, some rows (or columns, depending on the selection model being accessed) might not be selected.

A current selection identifies a minimum index, a maximum index, an anchor index, and a lead index. The minimum index is the index of the topmost row or leftmost column in the current selection interval. Similarly, the maximum index is the index of the bottommost row or rightmost column. The anchor index is the index of the topmost row or leftmost column in the bottommost row selection interval or rightmost column selection interval of the current selection interval. Finally, the lead index is the index of the bottommost row or rightmost column in the bottommost row selection interval or rightmost column selection interval of the current selection interval. That's quite a mouthful! The getMinimumIndex(), getMaximumIndex(), getAnchorIndex(), and getLeadIndex() methods retrieve the minimum, maximum, anchor, and lead indexes, respectively. By the way, the getAnchorIndex() and getLeadIndex() methods have "set" method counterparts.

Finally, what does adjusting mean? Adjusting means that ListSelectionListener's valueChanged(ListSelectionEvent) method is not called for every intermediate selection change during a selection drag operation.

The best way to become familiar with the various selection model concepts is to study source code that uses those concepts. Listing 9 presents source code to a TableDemo9 application that does just that. TableDemo9's source code shows how to attach a listener to each of the row and column selection models, and how to interrogate the columns and rows selected in each listener. Also, TableDemo9 includes source code that adds additional buttons to its GUI. Those buttons make it possible to choose a selection mode: single selection, single interval selection, or multiple interval selection. (By default, TableDemo9's selection mode is multiple interval. Also, it selects rows.)

Listing 9: TableDemo9.java

// TableDemo9.java

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

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

class TableDemo9 extends JFrame implements ActionListener
{
  JTable jt;

  TableDemo9 (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));

   // Register a RowListener object as a listener for selection
   // events originating from the row selection model.

   jt.getSelectionModel ().
     addListSelectionListener (new RowListener (jt));

   // Register a ColumnListener object as a listener for selection
   // events originating from the column selection model.

   jt.getColumnModel ().getSelectionModel ().
     addListSelectionListener (new ColumnListener (jt));

   // Add the table to the north portion of the frame window's
   // content pane.

   getContentPane ().add (jt, BorderLayout.NORTH);

   // Create a panel for positioning two panels of buttons.

   JPanel jp1 = new JPanel ();
   jp1.setLayout (new BorderLayout ());

   // Create a panel for positioning one row of buttons.

   JPanel jp2 = new JPanel ();

   // Create a "Row Selection Only" button, register the current
   // TableDemo9 object as a listener to that button's action
   // events, and add that button to the panel.

   JButton jb = new JButton ("Row Selection Only");
   jb.addActionListener (this);
   jp2.add (jb);

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

   jb = new JButton ("Column Selection Only");
   jb.addActionListener (this);
   jp2.add (jb);

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

   jb = new JButton ("Row and Column Selection");
   jb.addActionListener (this);
   jp2.add (jb);

   // Add the jp2 panel to the north region of the jp1 panel.

   jp1.add (jp2, BorderLayout.NORTH);

   // Create a panel for positioning one row of buttons.

   jp2 = new JPanel ();

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

   jb = new JButton ("Single Selection");
   jb.addActionListener (this);
   jp2.add (jb);

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

   jb = new JButton ("Single Interval");
   jb.addActionListener (this);
   jp2.add (jb);

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

   jb = new JButton ("Multiple Intervals");
   jb.addActionListener (this);
   jp2.add (jb);

   // Add the jp2 panel to the south region of the jp1 panel.

   jp1.add (jp2, BorderLayout.SOUTH);

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

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

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

   setSize (600, 275);

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

   // Enable row and/or column selection, or set the selection mode,
   // as appropriate.

   if (label.equals ("Row Selection Only"))
   {
     jt.setRowSelectionAllowed (true);
     jt.setColumnSelectionAllowed (false);
   }
   else
   if (label.equals ("Column Selection Only"))
   {
     jt.setColumnSelectionAllowed (true);
     jt.setRowSelectionAllowed (false);
   }
   else
   if (label.equals ("Row and Column Selection"))
   {
     jt.setRowSelectionAllowed (true);
     jt.setColumnSelectionAllowed (true);
   }
   else
   if (label.equals ("Single Selection"))
     jt.setSelectionMode (ListSelectionModel.SINGLE_SELECTION);
   else
   if (label.equals ("Single Interval"))
     jt.setSelectionMode (ListSelectionModel.
                SINGLE_INTERVAL_SELECTION);
   else
     jt.setSelectionMode (ListSelectionModel.
                MULTIPLE_INTERVAL_SELECTION);

   // Remove the current selection to prevent confusion.

   jt.clearSelection ();
  }

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

   new TableDemo9 ("Table Demo #9");
  }
}

class ColumnListener implements ListSelectionListener
{
  private JTable jt;

  ColumnListener (JTable jt)
  {
   this.jt = jt;
  }

  public void valueChanged (ListSelectionEvent e)
  {
   if (e.getValueIsAdjusting ())
     return;

   int [] cols = jt.getSelectedColumns ();

   for (int i = 0; i < cols.length; i++)
      System.out.println ("Selected column = " + cols [i]);

   System.out.println ("CL: First index = " + e.getFirstIndex ());
   System.out.println ("CL: Last index = " + e.getLastIndex () +
             "\n");
  }
}

class RowListener implements ListSelectionListener
{
  private JTable jt;

  RowListener (JTable jt)
  {
   this.jt = jt;
  }

  public void valueChanged (ListSelectionEvent e)
  {
   if (e.getValueIsAdjusting ())
     return;

   int [] rows = jt.getSelectedRows ();

   for (int i = 0; i < rows.length; i++)
      System.out.println ("Selected row = " + rows [i]);

   System.out.println ("RL: First index = " + e.getFirstIndex ());
   System.out.println ("RL: Last index = " + e.getLastIndex () +
             "\n");
  }
}

When rows, columns, or cells are selected, appropriate listeners are called that print selection information to the standard output device. To get comfortable with that information, consider an example. Suppose that you start TableDemo9 and press the Column Selection Only button. Then suppose that you select the cell in row 0 and column 1. When you do that, the next-to-leftmost column highlights and the following selection information appears on the standard output device:

Selected row = 0

Selected column = 1

First, the listener for row model events is called. It specifies the selected row as row 0. Second, the listener for column model events is called. It specifies the selected column as column 1.

Moving right along, suppose that you press a Shift key and the right arrow key. Now columns 1 and 2 highlight, and the following information appears on the standard output device:

Selected column = 1
Selected column = 2

The information shows that the column listener is called. Also, that information shows that both columns 1 and 2 are selected. Why has the row listener not been called? It is redundant to call the row listener because row selection information has not changed.

Suppose that you press the Ctrl key and click the cell at column 6 and row 6. That column highlights and the following information is sent to the standard output device:

Selected row = 0
Selected row = 6

Selected column = 1
Selected column = 2
Selected column = 6

Notice that the row listener is called. It outputs row 0 and row 6 as the only two selected rows. The column listener is called and outputs column numbers 1, 2, and 6 as the three selected columns. To see what the table component looks like, check out Figure 9.

Figure 9 After the previous exercise, columns 1, 2, and 6 are selected, and (row 6, column 6) contains the focused cell.

  • + Share This
  • 🔖 Save To Your Account