Home > Java > javaTutorial > body text

How to create a Java table using JTable

藏色散人
Release: 2019-01-17 15:15:29
Original
4908 people have browsed it

Java provides a useful class called JTable that allows you to create tables when developing graphical user interfaces using Java's Swing API components. You can let users edit the data or just view the data. Note that the table doesn't actually contain data - it's purely a display mechanism.

How to create a Java table using JTable

Note: As with any Swing GUI, you need to create a container to display the JTable.

Using arrays to store table data

A simple way to provide data for the JTable class is to use two arrays. The first one saves the column names in a String array:

String[] columnNames = {"First Name", "Surname", "Country"
, "Event", "Place", "Time", "World Record" };
Copy after login

The second array is a two-dimensional object array used to save the table's data. For example, this array includes six Olympic swimmers:

Object[][] data = {
{"César Cielo", "Filho", "Brazil", "50m freestyle",1 , "21.30", false },
{"Amaury", "Leveaux", "France", "50m freestyle", 2, "21.45", false },
{"Eamon", "Sullivan", "Australia", "100m freestyle", 2, "47.32", false },
{"Michael", "Phelps", "USA", "200m freestyle", 1, "1:42.96", false },
{"Ryan", "Lochte", "USA", "200m backstroke", 1, "1:53.94", true },
{"Hugues", "Duboscq", "France", "100m breaststroke", 3, "59.37", false }
};
Copy after login

The key here is to ensure that both arrays have the same number of columns.

Building JTable

Once you have your data, creating a table is a simple task. Just call the JTable constructor and pass it the two arrays:

JTable table = new JTable(data, columnNames);
Copy after login

You may want to add scroll bars to ensure the user can see all the data. To do this, put its JTable into a JScrollPane:

JScrollPane tableScrollPane = new JScrollPane(table);
Copy after login

Now when the table is displayed, you will see the columns and rows of data and can scroll up and down.

The JTable object provides an interactive table. If you double-click any cell, you will be able to edit the contents - although any edits only affect the GUI, not the underlying data. (An event listener needs to be implemented to handle changes to data.).

To change the width of a column, hover over the edge of the column header and drag it back and forth. To change the order of columns, click and hold on the column heading, then drag it to a new location.

Sort columns

To add the ability to sort rows, call the setAutoCreateRowSorter method:

table.setAutoCreateRowSorter(true);
Copy after login

When this method is set to true , you can click a column header to sort the rows based on the contents of the cells below that column.

Change the appearance of the table

To control the visibility of the grid lines, use the following setShowGrid method:

table.setShowGrid(true);
Copy after login

To completely change the color of the table , please use the setBackground and setGridColor methods:

table.setGridColor(Color.YELLOW);
table.setBackground(Color.CYAN);
Copy after login

By default, the column widths of the table are equal. If the container the table is in is resizable, the width of the columns will expand and contract, and the container will grow larger or smaller. If the user resizes the column, the width of the right column will change to accommodate the new column size.

You can use the setPreferredWidth method or column to set the initial column width. Use the TableColumn class to first get a reference to the column, then use the setPreferredWidth method to set the size:

TableColumn eventColumn = table.getColumnModel().getColumn(3);
eventColumn.setPreferredWidth(150);
TableColumn placeColumn = table.getColumnModel().getColumn(4);
placeColumn.setPreferredWidth(5);
Copy after login

Select row

By default, users can do this in one of the following three ways 1. Select a table row:

To select a single row, click a table cell in that row.

To select multiple consecutive rows, drag the mouse over multiple rows, or click the table cell with Shift Cell pressed.

To select multiple, non-contiguous rows, hold down the Control key (Command key on Mac) while clicking a table cell.

Using the table model

If you want a simple string-based table that can be edited, then using several arrays as the table data can be useful. If you look at the data array we created, the other data types it contains are Strings - the Place column contains ints and the World Record column contains booleans. However, both columns are displayed as strings. To change this behavior, create a table model.

The table model manages the data to be displayed in the table. To implement a table model, you can create a class that extends the AbstractTableModel class:

public abstract class AbstractTableModel extends Object implements TableModel, Serializable{
public int getRowCount();
public int getColumnCount();
public Object getValueAt(int row, int column);
public String getColumnName(int column;
public boolean isCellEditable(int rowIndex, int columnIndex);
public Class getColumnClass(int columnIndex);
}
Copy after login

The six methods above are the ones used in this step-by-step guide, but the AbstractTableModel class defines many more methods that can be used to manipulate JTables data in the object. When extending a class to use AbstractTableModel, you only need to implement the getRowCount, getColumnCount and getValueAt methods.

Create a new class that implements the above five methods:

class ExampleTableModel extends AbstractTableModel{
String[] columnNames = {"First Name", "Surname", "Country"
, "Event", "Place", "Time", "World Record" };
Object[][] data = {
{"César Cielo", "Filho", "Brazil", "50m freestyle",1 , "21.30", false },
{"Amaury", "Leveaux", "France", "50m freestyle", 2, "21.45", false },
{"Eamon", "Sullivan", "Australia", "100m freestyle", 2, "47.32", false },
{"Michael", "Phelps", "USA", "200m freestyle", 1, "1:42.96", false },
{"Larsen", "Jensen", "USA", "400m freestyle", 3, "3:42.78", false },
};
@Override
public int getRowCount()
{
return data.length;
}
@Override
public int getColumnCount()
{
return columnNames.length;
}
@Override
public Object getValueAt(int row, int column)
{
return data[row][column];
}
@Override
public String getColumnName(int column) {
return columnNames[column];
}@Override
public Class getColumnClass(int c) {
return getValueAt(0, c).getClass();
}@Override
public boolean isCellEditable(int row, int column)
{
if (column == 1 || column == 2)
{
return false;
}
else
{
return true;
}
}
}
Copy after login

In this example, it makes sense for the ExampleTableModel class to hold two strings containing the table data . Then, the getRowCount, getColumnCount, getValueAt and getColumnName methods can use the array to provide the values ​​for the table. Also, note how the isCellEditable method is written to disable editing of the first two columns.

Now, JTable we can use the following ExampleTableModel class instead of using two arrays to create the object:

JTable table = new JTable(new ExampleTableModel());
Copy after login

When the code runs, you will see that the JTable object is using the table model because there is no table The cells are editable and column names are used correctly. If the getColumnName method has not been implemented, the column names on the table will appear as the default names of A, B, C, D, etc.

我们现在考虑一下该方法 getColumnClass。仅这一点使得表模型值得实现,因为它为JTable对象提供了每列中包含的数据类型。如果您还记得,对象数据数组有两列不是String数据类型:Place包含int的World Record列和包含的列booleans。了解这些数据类型会更改JTable对象为这些列提供的功能。运行带有表模型的示例表代码意味着该World Record列实际上将是一系列复选框。

添加ComboBox编辑器

您可以为表中的单元格定义自定义编辑器。例如,您可以使组合框替换字段的标准文本编辑。

以下是使用JComboBoxcountry字段的示例 :

String[] countries = {"Australia", "Brazil", "Canada", "China"
,"France", "Japan", "Norway", "Russia", "South Korea"
, "Tunisia", "USA"};
JComboBox countryCombo = new JComboBox(countries);
Copy after login

要设置country列的默认编辑器,请使用TableColumn该类获取对country列的引用,并使用该setCellEditor方法将该列设置JComboBox为单元格编辑器:

TableColumn countryColumn = table.getColumnModel().getColumn(2);
countryColumn.setCellEditor(new DefaultCellEditor(countryCombo));
Copy after login

The above is the detailed content of How to create a Java table using JTable. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!