I have a JTable
which I want to have left-click and right-click JPopupMenu
on it. Normaly by left-click on the JTable you can select a row. I would like to do the same with right-click plus show up a popup menu. Does anybody know how to do this?
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());
}
}
});
please read my question JTable with JPopupMenu
most important is ListSelectionModel 's type
minor for your question, but both answers there are correct and great
您可以使用鼠标侦听器中的JTable.rowAtPoint(event.getPoint())轻松轻松地确定单击的行。
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.