1

我有一个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());
           }
       }
   });
4

3 回答 3

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());
       }
   }
});
于 2012-06-29T13:53:03.430 回答
1
于 2012-06-29T13:47:05.127 回答
1

您可以在鼠标侦听器中使用 JTable.rowAtPoint(event.getPoint()) 轻松确定单击的行。

于 2012-06-29T13:51:45.843 回答