我是Swing的新用户,非常绿色。我设法使用java.sun教程中的示例创建了一个表类,并设法将数据动态加载到其中。我希望能够通过显示一个对话框来对行上的单击作出反应。如何添加将识别所选行号的事件处理程序?
主要功能代码:
public static void main(String[] args) {
javax.swing.SwingUtilities.invokeLater(new Runnable() {
public void run() {
try {
MainWindow window = new MainWindow();
window.frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
//Create and set up the content pane.
createAndShowGUI();
//...
}
}
}
}
和
private static void createAndShowGUI() {
//Create and set up the window.
JFrame frame = new JFrame("Data Table");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
//Create and set up data of the content pane.
TableClass mainTable = new TableClass(fh.getColNames(), fh.getTableContent());
mainTable.setOpaque(true);
frame.setContentPane(mainTable);
//Display the window.
frame.pack();
frame.setVisible(true);
}
谢谢
答案 0 :(得分:5)
table.addMouseListener(new MouseAdapter() {
@Override
public void mouseClicked(MouseEvent e) {
if (SwingUtilities.isLeftMouseButton(e) && e.getClickCount() == 1) {
int selectedRowIndex = table.getSelectedRow();
//show your dialog with the selected row's contents
}
}
});
答案 1 :(得分:1)
有几点。
Bozhidar Batsov的回答是正确的。但是,您可能不一定要引用该表(例如,如果您的鼠标侦听器位于另一个类或其他类中)。点是,表可以从MouseEvent的getSource()方法中找到。您可以安全地将其转换为JTable。
此外,如果尚未在表上实际选择任何行,则table.getSelectedRow()可能返回-1。例如,如果用户点击表格的“空白”(网格外的区域,但仍在文本区域中),则会发生这种情况。请务必在代码中测试-1。