Search code examples
javaswingjtableillegalstateexceptionjpopupmenu

MouseListener is giving problems with show() method


I want to display a small context menu when a user right clicks a table row in my application. My plan was to use a custom made MouseListener for this that calls the show() method. Here is my code:

import java.awt.Point;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import javax.swing.JMenuItem;
import javax.swing.JPopupMenu;
import javax.swing.JTable;
import javax.swing.SwingUtilities;

class TableMouseListener extends MouseAdapter {
public void mousePressed(MouseEvent e) {
    JTable table = (JTable)(e.getSource());
    Point p = e.getPoint();
    int row = table.rowAtPoint(p);
    int col = table.columnAtPoint(p);

// The autoscroller can generate drag events outside the Tables range.
if ((col == -1) || (row == -1)) {
        return;
}

    if (SwingUtilities.isRightMouseButton(e)) {
        JPopupMenu pop = new JPopupMenu("Row "+row);
        JMenuItem menu1 = new JMenuItem("Wijzigen");
        menu1.addActionListener(new ActionListener(){
            public void actionPerformed(ActionEvent e){
                //do things, still have to make that
            }
        });
        pop.show(menu1, p.x, p.y);

    }
}
}

Now my problem is: when i run my application, and I right click a table row, it pops out this error:

Exception in thread "AWT-EventQueue-0" java.awt.IllegalComponentStateException: component must be showing on the screen to determine its location
at java.awt.Component.getLocationOnScreen_NoTreeLock(Unknown Source)
at java.awt.Component.getLocationOnScreen(Unknown Source)
at javax.swing.JPopupMenu.show(Unknown Source)
at TableMouseListener.mousePressed(TableMouseListener.java:34)

What exactly is going wrong here?


Solution

    • JMenuItem isn't added to the JPopup, then JMenuItem shoudn't be isDisplayable

    • prepare this container, dont't to create on fly ,

    • create whole popup container as local variable or as returns from class, void, whatever

      a) prepare with JMenuItems too

      b) override maybeShowPopup, then there you can manage whatever (must be done on EDT)

    • rest of importantn methods