Note that there are some explanatory texts on larger screens.

plurals
  1. POHow can I create a "Drop-Down" menu in a Java Swing toolbar?
    text
    copied!<p>I've created a drop-down menu on my Swing JToolBar. But it doesn't create behave the way I want. I'm aiming for it to work like Firefox's "Smart Bookmarks" button.</p> <p>It disappears when the user selects a menu item: CORRECT!</p> <p>It disappears when the user presses ESC: CORRECT!</p> <p>It disappears when the user clicks somewhere in the main frame outside of the menu: CORRECT!</p> <p>But it doesn't disappear when the user clicks a second time on the button that shows the drop-down menu: INCORRECT... :-(</p> <p>My question is how can I add this behaviour, that it does disappear when the clicks on the button that shows the menu a second time.</p> <p>Here's my current code, from Java 6 on the Mac:</p> <pre><code>import javax.swing.*; import javax.swing.event.PopupMenuEvent; import javax.swing.event.PopupMenuListener; import java.awt.*; import java.awt.event.ItemEvent; import java.awt.event.ItemListener; public class ScratchSpace { public static void main(String[] arguments) { SwingUtilities.invokeLater(new Runnable() { public void run() { JFrame frame = new JFrame("Toolbar with Popup Menu demo"); final JToolBar toolBar = new JToolBar(); toolBar.add(createMoreButton()); final JPanel panel = new JPanel(new BorderLayout()); panel.add(toolBar, BorderLayout.NORTH); panel.setPreferredSize(new Dimension(600, 400)); frame.getContentPane().add(panel); frame.pack(); frame.setLocationRelativeTo(null); frame.setVisible(true); } }); } private static AbstractButton createMoreButton() { final JToggleButton moreButton = new JToggleButton("More..."); moreButton.addItemListener(new ItemListener() { public void itemStateChanged(ItemEvent e) { if (e.getStateChange() == ItemEvent.SELECTED) { createAndShowMenu((JComponent) e.getSource(), moreButton); } } }); moreButton.setFocusable(false); moreButton.setHorizontalTextPosition(SwingConstants.LEADING); return moreButton; } private static void createAndShowMenu(final JComponent component, final AbstractButton moreButton) { JPopupMenu menu = new JPopupMenu(); menu.add(new JMenuItem("Black")); menu.add(new JMenuItem("Red")); menu.addPopupMenuListener(new PopupMenuListener() { public void popupMenuWillBecomeVisible(PopupMenuEvent e) { } public void popupMenuWillBecomeInvisible(PopupMenuEvent e) { moreButton.setSelected(false); } public void popupMenuCanceled(PopupMenuEvent e) { moreButton.setSelected(false); } }); menu.show(component, 0, component.getHeight()); } } </code></pre>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload