问题
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?
回答1:
JMenuItem
isn't added to theJPopup
, thenJMenuItem
shoudn't beisDisplayable
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
toob) override
maybeShowPopup
, then there you can manage whatever (must be done on EDT)rest of importantn methods
回答2:
You are trying to display JPopupMenu (pop) relatively to the JMenuItem (menu1) component. But JMenuItem is not visible in the moment when you call popupmenu show
method and it fails to determine JMenuItem location on screen (ofcourse, it is not shown on the screen yet).
You have to use some visible component in the popupmenu show
method as the first argument (for example some button that is added to displayed frame or any other actually visible component). You can also pass null to place the popup menu relatively to the (0;0) coordinate (upper-left screen corner).
来源:https://stackoverflow.com/questions/13161251/mouselistener-is-giving-problems-with-show-method