我想在用户右键单击我的应用程序中的表格行时显示一个小的上下文菜单。我的计划是为此使用定制的 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)
这里到底出了什么问题?
最佳答案
您正在尝试相对于 JMenuItem (menu1) 组件显示 JPopupMenu (pop)。但是当你调用 popupmenu show
方法时,JMenuItem 是不可见的,它无法确定 JMenuItem 在屏幕上的位置(当然,它还没有显示在屏幕上)。
您必须在 popupmenu show
方法中使用一些可见组件作为第一个参数(例如一些添加到显示框架的按钮或任何其他实际可见组件).您还可以传递 null 以相对于 (0;0) 坐标(屏幕左上角)放置弹出菜单。
关于java - MouseListener 给 show() 方法带来了问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13161251/