Java Reference
In-Depth Information
javax.swing.ListSelectionModel.SINGLE_SELECTION
being passed to
selectionMode
.
When the application starts running, the first table row (Mercury) should be high-
lighted(tocorrespondwiththedisplayedMercuryimage).Thistaskisaccomplishedby
invoking
JTable
's
void setRowSelectionInterval(int index0, int
index1)
method. Because only row 0 (the first or topmost row) needs to be selec-
ted, this value to passed to both
index0
and
index1
. (
setRowSelectionIn-
terval()
lets you select multiple rows, but only when the selection mode isn't
SINGLE_SELECTION
.)
The
SwingCanvas
component initially displays an image of Mercury. When the
userselectsanothertablerow,thatrow'splanetimagemustbedisplayed.Thistaskisac-
complished by registering a
javax.swing.event.ListSelectionListener
implementation instance with the table component's
ListSelectionModel
im-
plementation instance, which
JTable
's
ListSelectionModel getSelec-
tionModel()
method returns.
ListSelectionListener
declares a
void
valueChanged(ListSelectionEvent lse)
method that's called whenever
the user selects a row. The selected row is obtained by calling
JTable
's
int
getSelectedRow()
method, which is used to index into
iiPhotos
, whose
ImageIcon
instanceispassedto
SwingCanvas
's
void setPhoto(ImageIcon
iiPhoto)
method, which causes the new photo to be displayed.
The architectural style that I chose for the
Planets
application is appropriate for
smalldatabasetablesthatcanfitentirelyinmemory.However,youmightrunintoasitu-
ationwhereyouneedtoobtaindatafromadatabasetablewithmillions(ormore)rows
and populate a table component with all this data. Because there isn't enough memory
to make this practical, what do you do?
Thesolutionistoreadonlyasmallnumberofrowsintoacache(perhapswithhelp
fromtheReferenceAPI—see
Chapter4
)andkeeptrackofthecurrentlocation.Forex-
ample, assuming that each rowhasaunique 1-based integer identifier,youmight spe-
cify an SQL statement such as
SELECT * FROM EMPLOYEE WHERE ID >=
20 && ID <= 30
to return those rows whose
ID
column contains one of the
integer values from 20 through 30. Also, check out “Java: Loading Large Data into
JTable or JList” (
http://www.snippetit.com/2009/11/java-loading-
large-data-into-jtable-or-jlist/
) to learn how to create an appropriate
table model for use in this situation.