Java Swing – JTable

JTable is a component that displays rows and columns of data. You can drag the cursor on column boundaries to resize columns. You can also drag a column to a new position. Depending on its configuration, it is also possible to select a row, column, or cell within the table, and to change the data within a cell.

JTable is conceptually simple. It is a component that consists of one or more columns of information. At the top of each column is a heading. In addition to describing the data in a column, the heading also provides the mechanism by which the user can change the size of a column or change the location of a column within the table. JTable does not provide any scrolling capabilities of its own. Instead, you will normally wrap a JTable inside a JScrollPane. JTable supplies several constructors:

JTable(Object data[][], Object colHeads[])

Here, data is a two-dimensional array of the information to be presented, and colHeads is a one-dimensional array with column headings.

JTable relies on three models.

1. TableModel – It is defined by the TableModel interface. This model defines those things related to displaying data in a two-dimensional format.

2. TableColumnModel – It is represented by TableColumnModel. JTable is defined in terms of columns, and it is TableColumnModel that specifies the characteristics of a column.

3. ListSelectionModel – It determines how items are selected, and it is specified by the ListSelectionModel.

General Procedure to use Table:

1. Create an instance of JTable.
2. Create a JScrollPane object, specifying the table as the object to scroll.
3. Add the table to the scroll pane.
4. Add the scroll pane to the content pane.

Example:

import java.awt.*;
import javax.swing.*;
public class Table extends JApplet
{
public void init()
{
try
{
SwingUtilities.invokeAndWait(new Runnable()
{
public void run()
{
makeGUI();
}
});
}
catch(Exception exc)
{
System.out.println("Can't create because of " + exc);
}
}
private void makeGUI()
{
String[] colHeads = { "Name", "Extension", "ID#" };
Object[][] data = {
{ "Justin", "4567", "865" },
{ "Michael", "7566", "555" },
{ "Selena", "5634", "587" },
{ "Rose", "7345", "922" },
{ "Akon", "1237", "333" },
{ "Jack", "5656", "314" },
{ "Matt", "5672", "217" },
{ "Charlie", "6741", "444" },
{ "Erwin", "9023", "519" },
{ "Ellen", "1134", "532" },
{ "Jennifer", "5689", "112" },
{ "Bob", "9030", "133" },
{ "Luis", "6751", "145" }
};
JTable table = new JTable(data, colHeads);
JScrollPane jsp = new JScrollPane(table);
add(jsp);
}
}