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. If you go with the default options, however, 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
two-dimensional 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.java import java.awt.*; import java.awt.event.*; import javax.swing.*; import javax.swing.table.*; public class DullShipTable { public static void main(String[] args) { // create some tabular data String[] headings = new String[] {"Number", "Hot?", "Origin", "Destination", "Ship Date", "Weight" }; Object[][] data = new Object[][] { { "100420", Boolean.FALSE, "Des Moines IA", "Spokane WA", "02/06/2000", new Float(450) }, { "202174", Boolean.TRUE, "Basking Ridge NJ", "Princeton NJ", "05/20/2000", new Float(1250) }, { "450877", Boolean.TRUE, "St. Paul MN", "Austin TX", "03/20/2000", ...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.
Read now
Unlock full access