Java Code Examples for javax.swing.plaf.basic.BasicCheckBoxMenuItemUI

The following examples show how to use javax.swing.plaf.basic.BasicCheckBoxMenuItemUI. These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source Project: java-swing-tips   Source File: MainPanel.java    License: MIT License 4 votes vote down vote up
private MainPanel() {
  super();
  // Java 9
  // UIManager.put("CheckBoxMenuItem.doNotCloseOnMouseClick", true);

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

  // Java 9
  // JCheckBoxMenuItem checkMenuItem = new JCheckBoxMenuItem("doNotCloseOnMouseClick");
  // checkMenuItem.putClientProperty("CheckBoxMenuItem.doNotCloseOnMouseClick", true);
  // popup.add(checkMenuItem);

  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) {
      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));
}