-1

I need to create a comboBox with multiple chechboxes in my java swing gui. My first thought was to create a custom comboBox with its own CellRenderer but then I decided to go with a more "friendly" solution and use JMenu with JCheckBox items inside.

The problem is, that when I create the menu and place it inside my JPanel, the menu is not active and it does not open when being clicked. Any ideas what may be the cause of this behavior? Is it even possible to use JMenu like this?

This is a sample of my code:

JMenu menu;
panelCenter.add(new JLabel("Selection"));;
panelCenter.add(prepareSelection(menu));

private JMenu prepareSelection(JMenu menu) {
        menu = new JMenu("Select items");

        for (int i = 0; i < 10; i++) {
           JCheckBoxMenuItem item = new JCheckBoxMenuItem("item " + i);
           menu.add(item);
        }

        return menu;
    }

Thanks for any help!

Andrew Thompson
  • 168,117
  • 40
  • 217
  • 433
Smajl
  • 7,555
  • 29
  • 108
  • 179
  • 1
    Seems [that](http://stackoverflow.com/questions/1573159/java-check-boxes-in-a-jcombobox) can help you. – alex2410 Apr 09 '15 at 09:21
  • 1
    *"Is it even possible to use JMenu like this?"* Why does `setJMenuBar` not work for this GUI? Perhaps the panel needs a [pop-up menu](https://docs.oracle.com/javase/8/docs/api/javax/swing/JPopupMenu.html) instead.. – Andrew Thompson Apr 09 '15 at 09:34

2 Answers2

2

The place to add a JMenuBar is not in the JPanel, but in the layeredPane. You should add the JMenuBar, and it will reside at the top of the layeredPane. The rest of it will be covered by your contentPane. Once the JMenuBar is up you can modify the JMenus and the JMenuItems any time.

Here is a picture from Ivor Horton's Beginning Java:enter image description here

Costis Aivalis
  • 13,680
  • 3
  • 46
  • 47
  • 1
    ..glad you reinstated that answer. :) – Andrew Thompson Apr 09 '15 at 09:46
  • Actually, I solved the problem by first creating a JMenuBar (which actually CAN be added to JPanel and then adding JMenu to it) – Smajl Apr 09 '15 at 10:16
  • You can nevertheless add a JMenuBar to the NORTH of a panel with BorderLayout and also have in parallel a JMenuBar in the layeredPane, where it is supposed to be. Still your application will look quite weird. It would be more "normal" to use a pop-up menu, like @AndrewThompson suggested above. – Costis Aivalis Apr 09 '15 at 19:37
0

Solved. First added JMenuBar to my JPanel and then add JMenus to it.

menuBar = new JMenuBar();
prepareSelection(menuInput); // prepare menus
prepareSelection(menuOutput);
panelCenter.add(menuBar);
Smajl
  • 7,555
  • 29
  • 108
  • 179