2013-05-21 73 views
1

我做了一個自定義JComboBox。爲此,我正在使用包含JCheckBoxMenuItemJPopupMenu。但顯然PopupMenuListenerpopupMenuWillBecomeInvisible正在JCheckBoxMenuItem改變之前運行。任何想法如何解決? 我不想爲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) {} 
} 

回答

3

一個「可能」的解決方案與一個雜牌,是用你的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()); 
    } 
    }); 
} 
+0

Nooo!你打了我一分鐘。+1 =) –

+0

謝謝!工作很好 – Grains