Java 类javax.swing.plaf.basic.BasicCheckBoxMenuItemUI 实例源码

项目:java-swing-tips    文件:MainPanel.java   
private MainPanel() {
    super();

    JToggleButton button = new JToggleButton("JPopupMenu Test");
    JPopupMenu popup = new JPopupMenu();
    TogglePopupHandler handler = new TogglePopupHandler(popup, button);
    popup.addPopupMenuListener(handler);
    button.addActionListener(handler);

    popup.add(new JCheckBox("JCheckBox") {
        @Override public void updateUI() {
            super.updateUI();
            setFocusPainted(false);
        }
        @Override public Dimension getMinimumSize() {
            Dimension d = getPreferredSize();
            d.width = Short.MAX_VALUE;
            return d;
        }
    });
    popup.add(makeStayOpenCheckBoxMenuItem("JMenuItem + JCheckBox"));
    popup.add(new JCheckBoxMenuItem("JCheckBoxMenuItem"));
    popup.add(new JCheckBoxMenuItem("keeping open #1")).addActionListener(e -> {
        System.out.println("ActionListener");
        Container c = SwingUtilities.getAncestorOfClass(JPopupMenu.class, (Component) e.getSource());
        if (c instanceof JPopupMenu) {
            ((JPopupMenu) c).setVisible(true);
        }
    });
    popup.add(new JCheckBoxMenuItem("keeping open #2") {
        @Override public void updateUI() {
            super.updateUI();
            setUI(new BasicCheckBoxMenuItemUI() {
                // https://stackoverflow.com/questions/3759379/how-to-prevent-jpopupmenu-disappearing-when-checking-checkboxes-in-it
                @Override protected void doClick(MenuSelectionManager msm) {
                    //super.doClick(msm);
                    System.out.println("MenuSelectionManager: doClick");
                    menuItem.doClick(0);
                }
            });
        }
    });

    setOpaque(true);
    setComponentPopupMenu(popup);
    add(button);
    setPreferredSize(new Dimension(320, 240));
}