Displaying Tables
Now that we’ve seen how to assemble a prototypical Swing
GUI, we can move on and start studying some more advanced Swing
programming topics. We’ll start with examples of some of the more
powerful, and therefore complicated, components. The JTable
class displays tabular data. It is
particularly easy to use if your data happens to be organized into
arrays of arrays. If this is not the case, however, you must implement
the javax.swing.table.TableModel
interface to serve as a translator between your data and the JTable
component.
Example
11-19, which is a listing of
PropertyTable.java, does exactly this. PropertyTable
is a subclass of JTable
that uses a custom TableModel
implementation to display a table
of the properties defined by a specified JavaBeans class (it uses the
java.beans
package, which we’ll see
more of in Chapter 15). The
example includes a main( )
method
so you can run it as a standalone application. Figure 11-16 shows the PropertyTable
class in action. When studying
this example, pay particular attention to the TableModel
implementation: the TableModel
is the key to working with the
JTable
component. Also note the
PropertyTable
constructor method
that uses the TableColumnModel
to
modify the default appearance of the columns in the table.
Figure 11-16. The PropertyTable application
Example 11-19. PropertyTable.java
package je3.gui; import java.awt.*; ...
Get Java Examples in a Nutshell, 3rd Edition now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.