JTable เป็นคลาสย่อยของ JComponent ใช้สร้างตารางแสดงข้อมูลใน หลายแถวและคอลัมน์ เมื่อเลือกค่าจาก JTable จะสร้าง TableModelEvent ซึ่งจัดการโดยการใช้ TableModelListener
ในโปรแกรมตัวอย่างนี้ เราจะแสดงข้อความ "No records available" เมื่อไม่มีแถวข้อมูลใน JTable
ตัวอย่าง
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.table.*;
public class NoRecordTableTest extends JFrame {
private JPanel panel;
private JTable table;
private JScrollPane scrollPane;
public NoRecordTableTest() {
panel = new JPanel();
panel.setLayout(new BorderLayout());
String columnNames[] = {"Column 1", "Column 2", "Column 3"};
String dataValues[][] = {};
table = new JTable(dataValues, columnNames);
JLabel label = new JLabel("No records available");
label.setSize(label.getPreferredSize());
table.add(label);
table.setFillsViewportHeight(true);
scrollPane = new JScrollPane(table);
panel.add(scrollPane, BorderLayout.CENTER);
panel.add(new Label("No records available"), BorderLayout.SOUTH);
add(panel);
setSize(400, 300);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLocationRelativeTo(null);
setVisible(true);
}
public static void main(String args[]) {
new NoRecordTableTest();
}
}
ผลลัพธ์
