当用户在我的应用程序中右键单击表格行时,我想显示一个小的上下文菜单。我的计划是使用为此定制MouseListener
的调用该方法的show()
方法。这是我的代码:
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);
}
}
}
现在我的问题是:当我运行我的应用程序时,我右键单击表格行,它会弹出这个错误:
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)
这里到底出了什么问题?