Java Reference
In-Depth Information
// Reset the table data
this.mainTable.setModel(this.tableData);
// Reselect the previous item if it still exists
for (int i = 0; i < this.mainTable.getRowCount(); i++) {
String selectedUpc = (String) mainTable.getValueAt(i, 0);
if (selectedUpc.equals(prevSelected) ) {
this.mainTable.setRowSelectionInterval(i,i);
break;
}
}
}
Notice that the
setupTable
method refreshes the
MainWindow
's
JTable
instance by calling
the
setTableModel
method. As soon as the table's internal
TableModel
is replaced, the View
will refresh and display the updated data set. If the
JTable
does not update its contents, the
updateUI
method can be called, effectively forcing the table to redisplay its contents.
Also notice that the
setupTable
method stores the last selected row before refreshing
the table model. After the table model is reset, the method loops through the new data
set and locates the previously selected row by the UPC number. After that, the table's
setRowSelectionInterval
method is called to reselect the previous row.
The JScrollPane
Occasionally we get a situation where we need to display more on the screen than will fit. For
the Denny's DVDs application, it is possible that there could be so many DVDs in the database
that displaying them all on screen simultaneously is impossible.
In these cases, we can add the component that is too large for the screen to a
JScrollPane
,
which will put scrollbars around the component,
where necessary
, to allow scrolling to a differ-
ent region and viewing the contents there. Note that, by default, the scrollbars are only shown
when needed—if they are not needed, they will not appear.
Listing 8-18 shows an example of an application where there is too much data to appear
in the desired text area, and the way this would appear on screen is shown in Figure 8-20.
Listing 8-18.
An Application That Has Too Much Data to Appear in the Window
import javax.swing.*;
public class MyFrame {
public static void main(String[] args) throws Exception {
JFrame theFrame = new JFrame();
theFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);