我有一个JTable
我想要左键单击并右键单击JPopupMenu
。
Normaly通过左键单击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());
}
}
});
答案 0 :(得分:4)
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());
}
}
});
答案 1 :(得分:1)
请阅读我的问题JTable with JPopupMenu
最重要的是ListSelectionModel的类型
对你的问题很轻微,但两个答案都是正确的,很好的
答案 2 :(得分:1)
您可以使用鼠标侦听器中的JTable.rowAtPoint(event.getPoint())轻松确定单击的行。