Search code examples
javaswingmenuparallel-processingsubmenu

How can I put two elements in parallel in a JFrameMenu submenu?


If I have the common JFrameMenu with "File","Edit","View"... let's say I want to have a sub-menu with a JTextField and a button to do something. How can I put both things in parallel?

The only thing I've been able to do is put them one after another or put a separator.

To explain better what I want I've drawn this, in red what I've been able to do just adding elements to the menu and in green what I want:

Thank you.


Solution

  • You can, in fact, simply put a JPanel in the menu:

    JTextField textField;
    JMenuBar menuBar = new JMenuBar();
    setJMenuBar(menuBar);
    
    JMenu fileMenu = new JMenu("File");
    menuBar.add(fileMenu);
    
    JMenuItem menuItem1 = new JMenuItem("Menu Item above");
    fileMenu.add(menuItem1);
    
    JSeparator separatorAbove = new JSeparator();
    fileMenu.add(separatorAbove);
    JPanel panel = new JPanel();
    fileMenu.add(panel);
    
    textField = new JTextField();
    panel.add(textField);
    textField.setColumns(10);
    
    JButton button = new JButton("New button");
    panel.add(button);
    
    JSeparator separatorBelow = new JSeparator();
    fileMenu.add(separatorBelow);
    
    JMenuItem menuItem2 = new JMenuItem("Menu Item below");
    fileMenu.add(menuItem2);
    

    which produces this:

    the output