O'Reilly logo

Java Swing by Dave Wood, Marc Loy, Robert Eckstein

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Selecting Table Entries

All this, and all we can do is render and edit data in a table. “What about selecting data?” you ask. Yes, we can do that, too. And, as you might expect, the ListSelectionModel (discussed in Chapter 7) drives us through these selections. Unlike most of the other components, however, the two-dimensional JTable has two selection models, one for the rows and one for the columns.

Figure 15.9 shows an application that allows you to turn on and off the various selections allowed on a table (cell, row, and column). As you select different rows and columns, two status labels show you the indices of the selected items.

A table that lets you select rows, columns, or cells

Figure 15-9.  A table that lets you select rows, columns, or cells

Let’s look at the code for this example. Most of the work is getting the interface you see running. Once that’s done, we attach our two reporting labels as listeners to the row selection and column selection models. The interesting part of the code is the ListSelectionListener, written as an inner class. This class tracks any ListSelectionModel, and every time it changes, updates a label with the currently selected indices. (Those indices are retrieved using the getSelectedIndices() method we wrote ourselves.) Since we rely on only the list selection model, we can use the same event handler for both the row and the column selections.

// SelectionExample.java // A test of the JTable class ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required