1

I am new to java swing class and was learning how to add menubars and menus in JFrame.

I have written a simple example but the JFrame is displayed empty and I don't know why because I have included setJMenuBar() method in my code then also menubar isn't visible.

Here is my code

import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
public class jmenuexample extends JFrame //implements ActionListener
{
    JLabel title;
    JMenuBar menubar;
    JMenu menu, submenu;
    JMenuItem menuItem;
    jmenuexample()
    {
        setTitle("JMenu Example");
        setSize(750, 450);
        //setLayout(null);
        setVisible(true);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        menubar = new JMenuBar();
        menu = new JMenu("File");
        menuItem = new JMenuItem("New\tCtrl+N");
        menu.add(menuItem);
        menuItem = new JMenuItem("Open\tCtrl+O");
        menu.add(menuItem);
        menuItem = new JMenuItem("Save\tCtrl+S");
        menu.add(menuItem);
        //menu.addSeparator();
        menuItem = new JMenuItem("Exit");
        menu.add(menuItem);
        menubar.add(menu);
        /*panel = new JPanel();
        panel.setLayout(new GridLayout());
        panel.setBounds(250,10, 400, 300);*/
        //add(menubar);
        //add(panel);
        this.setJMenuBar(menubar);
    }
    public static void main(String argv[])
    {
        new jmenuexample();
    }
}

And here is the output of this code.

Screenshot of output

Ole V.V.
  • 81,772
  • 15
  • 137
  • 161
Riya Patel
  • 77
  • 9
  • 1
    Don't add "Ctrl_O" as part of the text of the menu item. Instead you need to use the `setAccelerator(...)` method of the `JMenuItem`. Read the section from the Swing tutorial on [How to Use Menus](http://docs.oracle.com/javase/tutorial/uiswing/components/menu.html) for more information and working examples. The tutorial will also help you better structure your class so your components are created on the `Event Dispatch Thread (EDT)`. Keep the tutorial link handy for all the Swing basics. – camickr Dec 16 '16 at 16:22
  • *"I am new to java swing"* So then start doing it right: Learn about [Java Naming conventions](http://www.oracle.com/technetwork/java/codeconventions-135099.html) and do not inherit from JFrame (http://stackoverflow.com/questions/15867148/why-do-we-need-to-extend-jframe-in-a-swing-application). – Timothy Truckle Dec 16 '16 at 16:28

1 Answers1

2

Because you are using setVisible(true); before you set this.setJMenuBar(menubar);

so chnage the order and setVisible(true); in the end.

Your code should be like this:

....
menubar.add(menu);
/*panel = new JPanel();
 panel.setLayout(new GridLayout());
 panel.setBounds(250,10, 400, 300);*/
//add(menubar);
//add(panel);
this.setJMenuBar(menubar);
setVisible(true);
....

Hope this can help you.

Youcef LAIDANI
  • 55,661
  • 15
  • 90
  • 140