java – 为什么没有为我的JPopupMenu调用componentHidden?
作者:互联网
我希望在我的JPopupMenu被隐藏时收到通知 – 无论是因为某个项目被选中,菜单被解除,还是被调用了setVisible(false).这是我的测试代码:
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class A extends ComponentAdapter implements Runnable, ActionListener {
private JButton b;
public static void main(String[] args) {
EventQueue.invokeLater(new A());
}
public void run() {
JFrame f = new JFrame("Test");
b = new JButton("Click me");
b.addActionListener(this);
f.add(b);
f.pack();
f.setVisible(true);
}
public void actionPerformed(ActionEvent e) {
JPopupMenu pm = new JPopupMenu();
pm.addComponentListener(this);
pm.add("Popup...");
pm.add("...menu!");
pm.show(b, 10, 10);
}
public void componentShown(ComponentEvent e) { System.out.println("componentShown"); }
public void componentHidden(ComponentEvent e) { System.out.println("componentHidden"); }
}
无论我如何与菜单交互,都没有调用两个ComponentListener方法.这是为什么?当我的JPopupMenu被隐藏时,是否有不同/更好/正确的方法来查找?
谢谢,
卡梅伦
解决方法:
pm.addPopupMenuListener(new PopupMenuListener() {
@Override
public void popupMenuCanceled(PopupMenuEvent e) {
System.out.println("cancelled");
}
@Override
public void popupMenuWillBecomeInvisible(PopupMenuEvent e) {
System.out.println("vanishing");
}
@Override
public void popupMenuWillBecomeVisible(PopupMenuEvent e) {
System.out.println("appearing");
}
});
编辑:哎呀,看起来有人选择在评论中回答.我的错.
编辑2:关于为什么ComponentListener没有发送菜单上的事件消失,这可能解释为:
The component-hidden and component-shown events occur only as the result of calls to a Component ‘s setVisible method. For example, a window might be miniaturized into an icon (iconified) without a component-hidden event being fired.
资料来源:ComponentListener tutorial(也许是非规范的,但是来自马的嘴.)
考虑到结合JPopupMenu的setVisible实现:
public void setVisible(boolean b) {
// Not supported for MenuComponents
}
你可能知道它是如何发生的,但不是为什么它会发生(理由是什么,哪里有正确记录?)
标签:java,swing,jpopupmenu 来源: https://codeday.me/bug/20190621/1258186.html