Vous êtes sur la page 1sur 13

JTable

The JTable is used to display and edit regular two-dimensional tables of cells. See How to Use Tables in
The Java Tutorial for task-oriented documentation and examples of using JTable.
The JTable has many facilities that make it possible to customize its rendering and editing but provides
defaults for these features so that simple tables can be set up easily. For example, to set up a table with
10 rows and 10 columns of numbers:
TableModel dataModel = new AbstractTableModel() {
public int getColumnCount() { return 10; }
public int getRowCount() { return 10;}
public Object getValueAt(int row, int col) { return new Integer(row*col); }
};
JTable table = new JTable(dataModel);
JScrollPane scrollpane = new JScrollPane(table);

JTables are typically placed inside of a JScrollPane. By default, a JTable will adjust its width such that a
horizontal scrollbar is unnecessary. To allow for a horizontal scrollbar, invoke setAutoResizeMode(int)
with AUTO_RESIZE_OFF. Note that if you wish to use JTable in a standalone view (outside of a
JScrollPane) and want the header displayed, you can get it using getTableHeader() and display it
separately.
To enable sorting and filtering of rows, use a RowSorter. You can set up a row sorter in either of two
ways:

Directly set the RowSorter. For example: table.setRowSorter(new TableRowSorter(model)).


Set the autoCreateRowSorter property to true, so that the JTable creates a RowSorter for
you. For example:setAutoCreateRowSorter(true).

The JTable uses integers exclusively to refer to both the rows and the columns of the model that it
displays. The JTable simply takes a tabular range of cells and uses getValueAt(int, int) to retrieve the
values from the model during painting. It is important to remember that the column and row indexes
returned by various JTable methods are in terms of the JTable (the view) and are not necessarily the
same indexes used by the model.
By default, columns may be rearranged in the JTable so that the view's columns appear in a different
order to the columns in the model. This does not affect the implementation of the model at all: when
the columns are reordered, the JTable maintains the new order of the columns internally and converts
its column indices before querying the model.
So, when writing a TableModel, it is not necessary to listen for column reordering events as the model
will be queried in its own coordinate system regardless of what is happening in the view. In the
examples area there is a demonstration of a sorting algorithm making use of exactly this technique to

interpose yet another coordinate system where the order of the rows is changed, rather than the order
of the columns.
Similarly when using the sorting and filtering functionality provided by RowSorter the underlying
TableModel does not need to know how to do sorting, rather RowSorter will handle it. Coordinate
conversions will be necessary when using the row based methods of JTable with the underlying
TableModel. All of JTables row based methods are in terms of the RowSorter, which is not necessarily
the same as that of the underlying TableModel. For example, the selection is always in terms of JTable
so that when using RowSorter you will need to convert using convertRowIndexToView or
convertRowIndexToModel. The following shows how to convert coordinates from JTable to that of the
underlying model:
int[] selection = table.getSelectedRows();
for (int i = 0; i < selection.length; i++) {
selection[i] = table.convertRowIndexToModel(selection[i]);
}
// selection is now in terms of the underlying TableModel
By default if sorting is enabled JTable will persist the selection and variable row heights in terms of the
model on sorting. For example if row 0, in terms of the underlying model, is currently selected, after the
sort row 0, in terms of the underlying model will be selected. Visually the selection may change, but in
terms of the underlying model it will remain the same. The one exception to that is if the model index is
no longer visible or was removed. For example, if row 0 in terms of model was filtered out the selection
will be empty after the sort.
JTree
A control that displays a set of hierarchical data as an outline. You can find task-oriented documentation
and examples of using trees in How to Use Trees, a section in The Java Tutorial.
A specific node in a tree can be identified either by a TreePath (an object that encapsulates a node and
all of its ancestors), or by its display row, where each row in the display area displays one node. An
expanded node is a non-leaf node (as identified by TreeModel.isLeaf(node) returning false) that will
displays its children when all its ancestors are expanded. A collapsed node is one which hides them. A
hidden node is one which is under a collapsed ancestor. All of a viewable nodes parents are expanded,
but may or may not be displayed. A displayed node is both viewable and in the display area, where it can
be seen.
The following JTree methods use "visible" to mean "displayed":
isRootVisible()
setRootVisible()
scrollPathToVisible()

scrollRowToVisible()
getVisibleRowCount()
setVisibleRowCount()

The next group of JTree methods use "visible" to mean "viewable" (under an expanded parent):

isVisible()
makeVisible()
If you are interested in knowing when the selection changes implement the TreeSelectionListener interface and add
the instance using the method addTreeSelectionListener. valueChanged will be invoked when the selection changes,
that is if the user clicks twice on the same node valueChanged will only be invoked once.
If you are interested in detecting either double-click events or when a user clicks on a node, regardless of whether or
not it was selected, we recommend you do the following:
final JTree tree = ...;
MouseListener ml = new MouseAdapter() {
public void mousePressed(MouseEvent e) {
int selRow = tree.getRowForLocation(e.getX(), e.getY());
TreePath selPath = tree.getPathForLocation(e.getX(), e.getY());
if(selRow != -1) {
if(e.getClickCount() == 1) {
mySingleClick(selRow, selPath);
}
else if(e.getClickCount() == 2) {
myDoubleClick(selRow, selPath);
}
}
}
};
tree.addMouseListener(ml);

NOTE: This example obtains both the path and row, but you only need to get the one you're interested in.
To use JTree to display compound nodes (for example, nodes containing both a graphic icon and text), subclass
TreeCellRenderer and use setCellRenderer(javax.swing.tree.TreeCellRenderer) to tell the tree to use it. To edit such
nodes, subclass TreeCellEditor and use setCellEditor(javax.swing.tree.TreeCellEditor).
Like all JComponent classes, you can use InputMap and ActionMap to associate an Action object with a KeyStroke and
execute the action under specified conditions.

Java and Databases (JDBC)


Java uses something called JDBC (Java Database Connectivity) to connect to databases. There's a JDBC API, which is the
programming part, and a JDBC Driver Manager, which your programmes use to connect to the database.
JDBC allows you to connect to a wide-range of databases (Oracle, MySQL, etc), but we're going to use the in-built
database you get with the Java/NetBeans software. The database is called Java DB, a version of Apache Derby. It runs
on a virtual server, which you can stop and start from within NetBeans.
To check that have everything you need, have a look at the Services tab in NetBeans. If you can't see the Services tab,
click Window from the NetBeans menu. From the Window menu, selectServices. You should see something like this:

Expand the Databases item to see a Java DB item, and a Drivers section:

The idea is that you start the Java DB virtual server, and then create and manipulate databases on the server. There
should be a database called sample already set up: (But don't worry if it's not there as we'll create our own database.)
In the image above, there are three databases: one is called sample, one is called test1, and the other is called exams.
For the project in this section, we're going to set up a new database. You'll then learn how to connect to this database
using Java code. The database we'll create will be a simple one-table affair, rather than multiple tables connected
together. You can indeed create multiple tables with Java DB, but we don't want to complicate things unnecessarily.
Starting the Virtual Server
The first thing to do is to start the server. So right click on Java DB. You'll see a menu appear. Select Start Server:

Have a look at the Output window and you'll see a few messages appear: (If you have a firewall running, you'll need to
let the Java DB server through.)

Once the server is up and running you can create databases. You'll see how to do that in the next lesson.
Now that your server has been started, you can go ahead and create a database.
To create a new database, right click on Java DB again. From the menu that appears, select Create Database:

When you click on Create Database, you'll see a dialogue box appear:

Type a name for your database in the first box. Call it Employees. Type any User Name and Password (something a bit
harder to crack than ours below!):

Click OK to create your database. It should then appear on the list:

Creating a Table in the Database


Now that the database has been created, you need to create a table in the database. To do so, right click on your
database. From the menu that appears select Connect:

When a connection is made, you'll see some default folders for Tables, Views, and Procedures (see further down if your
screen is not like this):

To create a new table in your database, right click the Tables folder. From the menu that appears, select Create Table:

If you don't see just the three folders above, but have something like this instead:

Click the APP entry, and then right-click on Tables.


When you click on Create Table, a dialogue box appears. Either this one:

Or this one:

From here, you not only type a name for your table, but you also set up the columns for the table.
In the Table Name at the top, delete the default name of Untitled. Type a new name for your table. Call it Workers.
You'll then have a table called Workers, which is in the Employees database.
But you can't click OK just yet as the table has no columns in it. We want to create columns with the following names:
ID
First_Name
Last_Name
Job_Title

The ID column will hold a unique identifying number. This will identify a row in the table. A column with unique data in
it is known as a Primary Key. Because it's the Primary Key, the column has to hold data: It can't hold a null value. (A null
value just means there's no information there.)
If your Create Table dialogue box is like the first one, then put a tick in the box for Key. When you tick the Key box,
check marks will also appear for Index and Unique. Now enter a title in the Column Name area. Type ID:

You now need to specify what kind of data is going in to the column. For our ID column, we'll haveIntegers. So scroll
along until you come to Data Type. Click on Data Type and a drop down list will appear. From the drop down list, select
Integers:

If your dialogue box is like the second one, then you need to click the Add Column button to add your first table
column. You'll see another dialogue box appear. This one:

The NAME is the name of the column in the table, like ID, First_Name, etc. The TYPE is the DATA TYPE, Integer,
VARCHAR, etc. Click the dropdown list to see more. Then check or uncheck the CONSTRAINTS boxes as indicated
below:

Click OK and you should be returned to the Create Table dialogue box:

We now have enough for the ID column in the table. Click the Add Column button on the right to add a new column to
the table. Enter the following values for this column (VARCHAR means a variable number of characters):
Key: Unchecked
Index: Unchecked
Null: Unchecked
Unique: Unchecked
Column Name: First_Name
Data Type: VARCHAR
Size: 20
For the third column in your table, enter the following values:
Key: Unchecked
Index: Unchecked
Null: Unchecked
Unique: Unchecked
Column Name: Last_Name
Data Type: VARCHAR
Size: 20
For the final column, here are the values to enter:
Key: Unchecked
Index: Unchecked
Null: Unchecked
Unique: Unchecked
Column Name: Job_Title
Data Type: VARCHAR
Size: 40
When you're finished, your Table dialogue box should look like this:

Click OK when you've entered all the information. Your table and table columns will then be created:

The next thing to do is to add some records to the database table. We'll do that next.

Vous aimerez peut-être aussi