如何在 Java 中以编程方式选择 JTable 的不同单元格?
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(); } }
输出
广告