如何在 Java 中检测 JTable 行的双击事件?
awtjavaobject oriented programmingprogrammingswing
JTable 是 JComponent 的子类,用于显示复杂的数据结构。JTable 可以遵循 模型视图控制器 (MVC) 设计模式来显示行和列中的数据。JTable 可以生成 TableModelListener、TableColumnModelListener、ListSelectionListener、CellEditorListener 和 RowSorterListener 接口。我们可以使用 MouseAdapter 类或 MouseListener 接口来检测 JTable 的双击事件。我们可以将 MouseEvent 类的 getClickCount() 值设置为 "2",以检测 JTable 的双击事件。
示例
import java.awt.*; import java.awt.event.*; import javax.swing.*; import javax.swing.table.*; public final class DoublClickJTableRowTest extends JFrame { private JTable table; private JScrollPane scrollPane; public DoublClickJTableRowTest() { setTitle("DoublClickJTableRow Test"); String[] columnNames = {"First Name", "Last Name"}; Object[][] data = {{"Raja", "Ramesh"}, {"Adithya", "Sai"}, {"Vineet", "Kumar"}, {"Krishna", "Kasyap"}}; table = new JTable(data, columnNames) { public boolean editCellAt(int row, int column, java.util.EventObject e) { return false; } }; table.setFocusable(false); table.addMouseListener(new MouseAdapter() { public void mouseClicked(MouseEvent me) { if (me.getClickCount() == 2) { // to detect doble click events JTable target = (JTable)me.getSource(); int row = target.getSelectedRow(); // select a row int column = target.getSelectedColumn(); // select a column JOptionPane.showMessageDialog(null, table.getValueAt(row, column)); // get the value of a row and column. } } }); scrollPane= new JScrollPane(table); add(scrollPane); setSize(375, 250); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); setLocationRelativeTo(null); setVisible(true); } public static void main(String[] args) { new DoublClickJTableRowTest(); } }