JPopupMenu on JTable -> Get the cell the menu was created on

前端 未结 3 946
别那么骄傲
别那么骄傲 2020-12-19 16:46

I have a situation where I have a popup menu created when a JTable is right clicked on. Standard way of creating the popup menu:

aJTable.setComponentPopupMen         


        
3条回答
  •  一整个雨季
    2020-12-19 17:19

    @MadProgrammer's suggestion of getPopupLocation looked promising, but I couldn't work out how to get the information across between the table and the actionEvent...

    I got around this by making sure that the row was selected when you rightclicked on it -> since the popup menu prevents the selection of the row, you can add in a mouse listener that makes sure the row gets selected no matter what click (left or right) is pressed.

    aTable.addMouseListener(new MouseAdapter() {
        @Override
        public void mousePressed(MouseEvent e) {
            int r = aTable.rowAtPoint(e.getPoint());
            if (r >= 0 && r < clt.getRowCount()) {
                aTable.setRowSelectionInterval(r, r);
            } else {
                aTable.clearSelection();
            }
        }
    });
    

    This means that in the rightClickMenuItem's action listener, you can grab the table's selected cell / row

    rightClickMenuItem.addActionListener(new AbstractAction() {
        @Override
        public void actionPerformed(ActionEvent e) {
            aTable.get details about the selected one....
        }
    });
    

    Too easy! Thanks everyone for the help.

提交回复
热议问题