Simon Peterkin
Simon Peterkin

Reputation: 1

Adding a JMenuItem to a JMenu Causes Menu Bar to Disappear

When I try to add a menu item to a menu, the menu bar disappears. The following code:

import javax.swing.JFrame;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;

public class WedgeTextFrame  {  

    public static void main(String[] args){

         JFrame f = new JFrame("Menu");
         f.setVisible(true);
         f.setSize(400,400);
         f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

         JMenuBar menubar = new JMenuBar();

         JMenu file = new JMenu("File");
         JMenu tools = new JMenu("Tools");
         menubar.add(file);
         menubar.add(tools);

         f.setJMenuBar(menubar);
    }
}

results in

image

When I add the following lines just after menubar.add(tools); that define and add a JMenuItem to a JMenu:

JMenuItem exit_item = new JMenuItem("Exit");
tools.add(exit_item);

The menu bar disappears. I am running Eclipse 2019-06 with JRE 1.8.0

Upvotes: 0

Views: 318

Answers (1)

George Z.
George Z.

Reputation: 6808

That's where the "All Swing applications must run on their own thread" part comes. Take a look at initial threads and the Event Dispatch Thread. Starting your application by calling SwingUtilities#invokeLater will solve your problem.

public static void main(String[] args) {
    SwingUtilities.invokeLater(() -> {
        JFrame f = new JFrame("Menu");
        f.setVisible(true);
        f.setSize(400, 400);
        f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        JMenuBar menubar = new JMenuBar();

        JMenu file = new JMenu("File");
        JMenu tools = new JMenu("Tools");
        menubar.add(file);
        menubar.add(tools);

        JMenuItem exit_item = new JMenuItem("Exit");
        tools.add(exit_item);

        f.setJMenuBar(menubar);
    });
}

I also advice you to frame.setVisible(true) after the whole frame is prepared:

SwingUtilities.invokeLater(() -> {
    JFrame f = new JFrame("Menu");
    f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

    //add stuff to frame

    f.setSize(400, 400);
    f.setVisible(true); //Here at the end
});

Upvotes: 1

Related Questions