O'Reilly logo

Java Swing by Dave Wood, Marc Loy, Robert Eckstein

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

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"); ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required