Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.1k views
in Technique[技术] by (71.8m points)

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

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.setComponentPopupMenu(rightClickMenu);

Now afterwards in the action that gets registered, I am unable to find out which cell was right clicked on to get that popup menu to appear.

rightClickMenuItem.addActionListener(new AbstractAction() {
    @Override
    public void actionPerformed(ActionEvent e) {
        // Work out what cell was right clicked to generate the menu
    }

});

Any ideas on how you do this?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...