Skip to Main Content
Java Swing, 2nd Edition
book

Java Swing, 2nd Edition

by Dave Wood, Robert Eckstein, Marc Loy, James Elliott, Brian Cole
November 2002
Intermediate to advanced content levelIntermediate to advanced
1278 pages
38h 26m
English
O'Reilly Media, Inc.
Content preview from Java Swing, 2nd Edition

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 rows and one for columns.

Figure 15-8 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-8. 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 updates a label with the currently selected indices every time it changes. (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 simple multiplication table with the ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Start your free trial

You might also like

Java Threads, 3rd Edition

Java Threads, 3rd Edition

Scott Oaks, Henry Wong

Publisher Resources

ISBN: 0596004087Errata PageSupplemental Content