Google Tag Manager

2024/03/31

Switching between JToolBar and JMenuBar

Click on the hamburger menu-like JButton placed on the JToolBar to switch this with the JMenuBar

Code

JMenuBar mainMenuBar = makeMenuBar();
JButton button = makeHamburgerMenuButton(mainMenuBar);
JMenuBar wrappingMenuBar = new JMenuBar();
wrappingMenuBar.add(makeToolBar(button));
EventQueue.invokeLater(() -> getRootPane().setJMenuBar(wrappingMenuBar));

PopupMenuListener handler = new PopupMenuListener() {
  @Override public void popupMenuWillBecomeVisible(PopupMenuEvent e) {
    // not need
  }

  @Override public void popupMenuWillBecomeInvisible(PopupMenuEvent e) {
    EventQueue.invokeLater(() -> {
      if (MenuSelectionManager.defaultManager().getSelectedPath().length == 0) {
        getRootPane().setJMenuBar(wrappingMenuBar);
      }
    });
  }

  @Override public void popupMenuCanceled(PopupMenuEvent e) {
    EventQueue.invokeLater(() -> getRootPane().setJMenuBar(wrappingMenuBar));
  }
};
for (int i = 0; i < mainMenuBar.getMenuCount(); i++) {
  mainMenuBar.getMenu(i).getPopupMenu().addPopupMenuListener(handler);
}
// ...
private JButton makeHamburgerMenuButton(JMenuBar menuBar) {
  JButton button = new JButton("Ξ") {
    @Override public Dimension getPreferredSize() {
      Dimension d = super.getPreferredSize();
      d.height = menuBar.getMenu(0).getPreferredSize().height;
      return d;
    }

    @Override public void updateUI() {
      super.updateUI();
      setContentAreaFilled(false);
      setFocusPainted(false);
      setBorder(BorderFactory.createEmptyBorder(0, 2, 0, 2));
    }
  };
  button.addActionListener(e -> {
    getRootPane().setJMenuBar(menuBar);
    getRootPane().revalidate();
    EventQueue.invokeLater(() -> menuBar.getMenu(0).doClick());
  });
  button.setMnemonic('\\');
  button.setToolTipText("Main Menu(Alt+\\)");
  return button;
}

References

No comments:

Post a Comment