Chapter 15. Tables

Tables represent one of the most common formats for viewing data. Database records are easy to sort and choose from a table. Statistics on disk usage can be displayed for several computers or several time periods all at once. Stock market quotes can be tracked. And where would sales presentations be without tables? Well, the JTable class in the Swing package now gives you access to a single component that can handle all of the preceding examples and more.

Without getting fancy, you can think of tables as an obvious expression of two-dimensional data. In fact, the JTable class has a constructor that takes an Object[][] argument and displays the contents of that two-dimensional array as a table with rows and columns. For example, Figure 15.1 shows how a table of string objects falls out very quickly.

Two-dimensional array of strings for data

Figure 15-1. Two-dimensional array of strings for data

This program was generated with very little code. All we did was set up a JTable object with an String[][] argument for the table data, and a String[] argument for the table’s headers. Rather than adding the table itself directly to our window, we enclose it in a scroll pane:

// SimpleTable.java
          // A test of the JTable class using default table models and a convenience // constructor. // import java.awt.*; import javax.swing.*; public class SimpleTable extends JFrame { public SimpleTable() { super("Simple JTable Test"); ...

Get Java Swing 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.