gpt4 book ai didi

java - 监听器在 Action 前运行

转载 作者:行者123 更新时间:2023-11-29 05:43:26 24 4
gpt4 key购买 nike

我制作了一个自定义的 JComboBox。为此,我使用了包含 JCheckBoxMenuItemJPopupMenu。但显然 PopupMenuListener popupMenuWillBecomeInvisibleJCheckBoxMenuItem 更改之前运行。任何想法如何解决?我不想向 JCheckBoxMenuItem 添加监听器。

public class ListenerTest  extends JFrame implements ActionListener, PopupMenuListener {

private JPopupMenu menu;
private List<JCheckBoxMenuItem> menuItems;

private JCheckBoxMenuItem i1;
private JCheckBoxMenuItem i2;
private JCheckBoxMenuItem i3;

public ListenerTest(){

// Create button
JButton b = new JButton("Click me!");
b.addActionListener(this);

// Create Popupmenu
menu = new JPopupMenu();
menu.addPopupMenuListener(this);

// Add CheckBoxes to PopupMenu
menuItems = new LinkedList<JCheckBoxMenuItem>();
i1 = new JCheckBoxMenuItem("1");
i2 = new JCheckBoxMenuItem("2");
i3 = new JCheckBoxMenuItem("3");
menu.add(i1);
menu.add(i2);
menu.add(i3);

this.add(b);
this.setDefaultCloseOperation(EXIT_ON_CLOSE);
this.pack();
this.setVisible(true);
}

public static void main(String[] args){
new ListenerTest();
}

@Override
public void actionPerformed(ActionEvent e) {
// Show PopupMenu when button is clicked
menu.show(this, 0, this.getHeight());
}

@Override
public void popupMenuWillBecomeVisible(PopupMenuEvent e) {}

@Override
public void popupMenuWillBecomeInvisible(PopupMenuEvent e) {
// Check which checkBoxes is checked when popup menu is closed(currently one step behind)
System.out.println(i1.isSelected());
System.out.println(i2.isSelected());
System.out.println(i3.isSelected());
}

@Override
public void popupMenuCanceled(PopupMenuEvent e) {}
}

最佳答案

一个“可能的”解决方案与杂乱无章,是使用您的 popupMenuWillBecomeInvisible(...) 但是将您的状态检查排队到 Swing 事件队列中,以便它稍后执行其操作,之后当前事件队列中的所有项目都已完成。但是,这不能保证有效。

@Override
public void popupMenuWillBecomeInvisible(PopupMenuEvent e) {

SwingUtilities.invokeLater(new Runnable() {
public void run() {
System.out.println(i1.isSelected());
System.out.println(i2.isSelected());
System.out.println(i3.isSelected());
}
});
}

关于java - 监听器在 Action 前运行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16673631/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com