Domanda

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());
           }
       }
   });
È stato utile?

Soluzione

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());
       }
   }
});

Altri suggerimenti

You can determine the clicked row easily enough using JTable.rowAtPoint(event.getPoint()) in your mouse listener.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top