Tables
Tables present information in orderly rows and columns. This is useful for presenting financial figures or representing data from a relational database. Like trees, tables in Swing are incredibly powerful and customizable. If you go with the default options, they’re also pretty easy to use.
The JTable class represents a
visual table component. A JTable is
based on a TableModel, one of a dozen
or so supporting interfaces and classes in the javax.swing.table
package.
A First Stab: Freeloading
JTable has one
constructor that creates a default table model for you from arrays of
data. You just need to supply it with the names of your column headers
and a 2D array of Objects
representing the table’s data. The first index selects the table’s row;
the second index selects the column. The following example shows how
easy it is to get going with tables using this constructor:
//file: DullShipTable.javaimportjava.awt.*;importjava.awt.event.*;importjavax.swing.*;importjavax.swing.table.*;publicclassDullShipTable{publicstaticvoidmain(String[]args){// create some tabular dataString[]headings=newString[]{"Number","Hot?","Origin","Destination","Ship Date","Weight"};Object[][]data=newObject[][]{{"100420",Boolean.FALSE,"Des Moines IA","Spokane WA","02/06/2000",newFloat(450)},{"202174",Boolean.TRUE,"Basking Ridge NJ","Princeton NJ","05/20/2000",newFloat(1250)},{"450877",Boolean.TRUE,"St. Paul MN","Austin TX","03/20/2000",newFloat ...