JTable เป็นคลาสย่อยของ JComponent สร้างตารางแสดงข้อมูลหลายแถวหลายคอลัมน์ เมื่อเลือกค่าจะสร้าง TableModelEvent จัดการโดย TableModelListener โดยทั่วไปผู้ใช้เลือกแถว/คอลัมน์เอง แต่เราสามารถเลือกเซลล์ ด้วยโปรแกรม (programmatically) ได้โดยใช้ 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();
}
}
ผลลัพธ์
