A JTable เป็นคลาสย่อยของ JComponent คลาสและสามารถใช้เพื่อสร้างตารางที่มีข้อมูลที่แสดงในหลายแถวและคอลัมน์ เมื่อค่าถูกเลือกจาก JTable TableModelEvent ถูกสร้างขึ้น ซึ่งจัดการโดยใช้ TableModelListener อินเทอร์เฟซ
โดยทั่วไป ผู้ใช้สามารถเลือกแถวและคอลัมน์ด้วยตนเองใน JTable ได้ เรายังสามารถเลือกเซลล์ต่างๆ ของ JTable ได้ โดยทางโปรแกรม โดยใช้ setRowSelectionInterval() และ setColumnSelectionInterval() วิธีการของ JTable ชั้นเรียน
ตัวอย่าง
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class JTableCellSelectionTest extends JFrame {
private JTable table;
public JTableCellSelectionTest() {
setTitle("JTableCellSelection Test");
Object[][] data = {{ "Raja", "Java", "Hyderabad"}, {"Vineet", "JavaScript", "Bangalore"},
{"Adithya", "Scala", "Chennai"}, {"Jai", "ServiceNow", "Pune"},
{"Chaitanya", "Python", "Noida"}, {"Krishna", "AI", "Mumbai"}};
String columns[] = {"Name", "Technology", "Location"};
table = new JTable(data, columns);
add(new JScrollPane(table));
table.setRowSelectionInterval(0, 2);
table.setColumnSelectionInterval(0, 2);
setSize(400, 300);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLocationRelativeTo(null);
setVisible(true);
}
public static void main(String []args) {
new JTableCellSelectionTest();
}
} ผลลัพธ์
