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

前端 未结 3 947
别那么骄傲
别那么骄傲 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:08

    Astonishing fact: with a componentPopupMenu installed, a mouseListener never sees the mouseEvent that is the popupTrigger (reason is that showing the componentPopup is handled globally by a AWTEventListener installed by BasicLookAndFeel, and that listener consumes the event).

    The only place which sees the mousePosition of that trigger is the getPopupLocation(MouseEvent), so the only reliable way to get hold of it (for doing location dependent config/actions) is @Mad's suggestion to override that method and store the value somewhere for later use.

    The snippet below uses a clientProperty as storage location:

    final JTable table = new JTable(new AncientSwingTeam()) {
    
        @Override
        public Point getPopupLocation(MouseEvent event) {
            setPopupTriggerLocation(event);
            return super.getPopupLocation(event);
        }
    
        protected void setPopupTriggerLocation(MouseEvent event) {
            putClientProperty("popupTriggerLocation", 
                    event != null ? event.getPoint() : null);
        }
    };
    JPopupMenu popup = new JPopupMenu();
    Action action = new AbstractAction("show trigger location") {
    
        @Override
        public void actionPerformed(ActionEvent e) {
            JPopupMenu parent = (JPopupMenu) SwingUtilities.getAncestorOfClass(
                    JPopupMenu.class, (Component) e.getSource());
            JTable invoker = (JTable) parent.getInvoker();
            Point p = (Point) invoker.getClientProperty("popupTriggerLocation");
            String output = p != null ? "row/col: " 
                 + invoker.rowAtPoint(p) + "/" + invoker.columnAtPoint(p) : null; 
            System.out.println(output);
        }
    };
    popup.add(action);
    popup.add("dummy2");
    table.setComponentPopupMenu(popup);
    

提交回复
热议问题