我有一个JTable
,我想在上面左键单击并右键单击JPopupMenu
。通常,通过左键单击JTable,您可以选择一行。我想通过右键单击并显示弹出菜单来做同样的事情。有人知道如何做到这一点吗?
table.addMouseListener(new MouseAdapter() {
@Override
public void mouseClicked(MouseEvent e) {
if (SwingUtilities.isRightMouseButton(e)) {
//this line gives wrong result because table.getSelectedRow() stay alwase on the same value
codeModel.setSelectedFileName(table.getValueAt(table.getSelectedRow(), 0).toString());
JPopupMenu popup = createRightClickPopUp();
popup.show(e.getComponent(), e.getX(), e.getY());
}else{
codeModel.setSelectedFileName(table.getValueAt(table.getSelectedRow(), 0).toString());
codeTextArea.setText(codeModel.getCodeContents());
}
}
});
table.addMouseListener(new MouseAdapter() {
@Override
public void mouseClicked(MouseEvent e) { //or mouseReleased(MouseEvent e)
if (SwingUtilities.isRightMouseButton(e)) {
//-- select a row
int idx = table.rowAtPoint(e.getPoint());
table.getSelectionModel().setSelectionInterval(idx, idx);
//---
codeModel.setSelectedFileName(table.getValueAt(table.getSelectedRow(), 0).toString());
JPopupMenu popup = createRightClickPopUp();
popup.show(e.getComponent(), e.getX(), e.getY());
}else{
codeModel.setSelectedFileName(table.getValueAt(table.getSelectedRow(), 0).toString());
codeTextArea.setText(codeModel.getCodeContents());
}
}
});
-
请阅读我的问题 JTable 与 JPopupMenu
-
最重要的是ListSelectionModel的类型
-
你的问题很小,但两个答案都是正确和伟大的
您可以在鼠标侦听器中使用 JTable.rowAtPoint(event.getPoint()) 轻松确定单击的行。