It’s hard for me to get a position . JPopupMenu
I need to right-click on the workspace, click on the button and then create the item in place right below the position of the previously displayed menu.
I tried to get the position of the menu itself and its elements,
but it gives me constant values around 0. (see comments in the code)
Due to the separation of problems , the menu is displayed in one class
and its actions are processed in another.
public final class MainFrameMenu
extends JPopupMenu
implements ActionListener {
private final MainFrame mainFrame;
private final JMenuItem item1 = new JMenuItem("add line");
private final JMenuItem item2 = new JMenuItem("add element");
public MainFrameMenu(MainFrame mainFrame) {
super("Main menu");
this.mainFrame = mainFrame;
item1.addActionListener(this);
item2.addActionListener(this);
add(item1);
add(item2);
}
@Override
public void actionPerformed(ActionEvent e) {
if (e.getSource() == item1) {
System.out.println(getLocation());
System.out.println(item1.getLocation());
mainFrame.addConnectionLine(getX(), getY());
}
}
}
public final class PopupMouseListener
extends MouseAdapter {
private final JPopupMenu menu;
public PopupMouseListener(JPopupMenu menu) {
this.menu = menu;
}
@Override
public void mousePressed(MouseEvent e) {
popup(e);
}
@Override
public void mouseReleased(MouseEvent e) {
popup(e);
}
private void popup(MouseEvent e) {
if (e.isPopupTrigger()) {
menu.show(e.getComponent(), e.getX(), e.getY());
}
}
}
, PopupMouseListener,
MainFrameMenu,
( PopupMouseListener ).