Using the JFC/Swing Packages |
With theJTable
class, you can display tables of data.JTable
doesn't contain or cache data; it's simply a view of your data. This lack of caching makesJTable
perform well, even when its data comes from a huge database.JTable
has too many features to be completely described in this tutorial. For more complete documentation of Swing tables, refer to the most current Swing Release Documentation.When you create a table, you need to supply the data for that table. Often, this means writing a table model -- a class that implements the
TableModel
interface. Swing includes two table model implementations:AbstractTableModel
andDefaultTableModel
. A table model contains methods for getting and setting data values, getting the number of rows (records) of data, and adding and removing table listeners. (Table listeners are objects such as theJTable
that are notified each time the data changes.)Here is a picture of an application that displays an uneditable table in a scroll pane:
Try this:
- Compile and run the application. The source file is
SimpleTableDemo.java
.
See Getting Started with Swing if you need help.- Click a cell.
The entire row is selected. This is intended to remind you thatJTable
implements a database browser, not a spreadsheet.- Position the cursor over the "First Name" heading. Now press the mouse button and drag the heading to the right.
As you can see, users can rearrange columns in tables. This flexible positioning is why columns are specified by objects (such as strings), instead of indexes (such as are used for rows).- Position the cursor just to the right of a heading. Now press the mouse button and drag to the right or left.
The column changes size.- Resize the window containing the table so that it's bigger than necessary to display the whole table.
The table cells stay the same size, and they're clustered at the upper left of the display area.
Below is the code from
SimpleTableDemo.java
that implements the table in the previous example.[Now show an editable table.]public class SimpleTableDemo extends JPanel { final Object[][] data = { {"Mary", "Campione", "Snowboarding", "5"}, {"Alison", "Huml", "Rowing", "3"}, {"Kathy", "Walrath", "Chasing toddlers", "2"}, {"Mark", "Andrews", "Speed reading", "20"}, {"Angela", "Lih", "Teaching high school", "4"} }; final Object[] columnNames = {"First Name", "Last Name", "Sport", "Est. Years Experience"}; public SimpleTableDemo() { JTable table = new JTable(data, columnNames); //Create the scroll pane and add the table to it. JScrollPane scrollPane = JTable.createScrollPaneForTable(table); //Add the scroll pane to this panel. setLayout(new GridLayout(1, 0)); add(scrollPane); } . . . }
Using the JFC/Swing Packages |