The code snippet presented below shows you how to create a simple JTable
component in a swing application. To create a JTable
component we initializes it using the constructor that accept two parameters.
The first parameter is the table’s row of data which type is Object[][]
, a two-dimensional array of Object
. The second parameter is the table’s column names which type is Object[]
, an array of object.
After the JTable
instance is created we places it inside a scroll pane component which in turn is added to the frame’s content pane.
package org.kodejava.example.swing;
import javax.swing.*;
import java.awt.*;
import java.text.MessageFormat;
import java.util.Calendar;
public class SimpleJTableDemo extends JFrame {
public SimpleJTableDemo() throws HeadlessException {
initializeUI();
}
private void initializeUI() {
// Defines table's column names.
String[] columnNames = {
"ID", "Name", "Date of Birth", "Sex"
};
// Defines table's data.
Object[][] rowData = {
{1, "Alice", createDOB(1980, Calendar.JANUARY, 1), "F"},
{2, "Bob", createDOB(1982, Calendar.JUNE, 21), "M"},
{3, "Carol", createDOB(1970, Calendar.OCTOBER, 12), "M"},
{4, "Mallory", createDOB(1988, Calendar.FEBRUARY, 19), "M"},
{5, "Ignasia", createDOB(1984, Calendar.NOVEMBER, 28), "F"}
};
// Initializes an instance of JTable and specifies the table
// data and column names. After that we place the table in a
// scroll pane.
JTable table = new JTable(rowData, columnNames);
JScrollPane pane = new JScrollPane(table);
// Sets the frame setting.
setTitle("Simple JTable Demo");
setSize(new Dimension(400, 200));
setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
setLayout(new BorderLayout());
getContentPane().add(pane, BorderLayout.CENTER);
}
private String createDOB(int year, int month, int day) {
Calendar calendar = Calendar.getInstance();
calendar.set(year, month, day);
return MessageFormat.format("{0,date,dd-MMM-yyyy}", calendar.getTime());
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
new SimpleJTableDemo().setVisible(true);
}
});
}
}
When we running the program we will see the following result:
Latest posts by Wayan (see all)
- How do I install Calibri font in Ubuntu? - January 24, 2021
- How do I create a generic class in Java? - January 1, 2021
- How do I convert java.util.TimeZone to java.time.ZoneId? - April 25, 2020