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.

Figure 15-1. A simple JTable with a two-dimensional array of strings for data
figs/swng2.1501.gif

This program was generated with very little code. All we did was set up a JTable object with a 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 scrollpane:

// 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");     setSize(300, 200);     setDefaultCloseOperation(EXIT_ON_CLOSE);     JTable jt = new JTable(new String[][] { {"This", "is"}, {"a", "Test"} },                            new String[] {"Column", "Header"});     JScrollPane jsp = new JScrollPane(jt);     getContentPane( ).add(jsp, BorderLayout.CENTER);   }   public static void main(String args[]) {     SimpleTable st = new SimpleTable( );     st.setVisible(true);   } }

As you can see, we rely entirely on the data models built for us and simply pass in our data (a String[][] object) and our column headers (a String[] object). JTable takes care of the rest. With the default models, you can select multiple rows, edit individual cells, and listen for selection events. But of course, you are not restricted to the default models, and you can produce some pretty interesting effects if you decide to roll your own.



Java Swing
Graphic Java 2: Mastering the Jfc, By Geary, 3Rd Edition, Volume 2: Swing
ISBN: 0130796670
EAN: 2147483647
Year: 2001
Pages: 289
Authors: David Geary

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net