How to create a JMenuBar Component in Java?


To create a JMenuBar component, use the JMenuBar class −

JMenuBar menuBar = new JMenuBar();

Now, create menus inside the MenuBar −

JMenu fileMenu = new JMenu("File");

Add the above menu to the MenuBar −

menuBar.add(fileMenu);

The following is an example to create a JMenuBar Component in Java −

Example

package my;
import java.awt.event.KeyEvent;
import javax.swing.JFrame;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
public class SwingDemo {
   public static void main(final String args[]) {
      JFrame frame = new JFrame("MenuBar Demo");
      frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
      JMenuBar menuBar = new JMenuBar();
      JMenu fileMenu = new JMenu("File");
      fileMenu.setMnemonic(KeyEvent.VK_F);
      menuBar.add(fileMenu);
      JMenuItem menuItem1 = new JMenuItem("New", KeyEvent.VK_N);
      fileMenu.add(menuItem1);
      JMenuItem menuItem2 = new JMenuItem("Open File", KeyEvent.VK_O);
      fileMenu.add(menuItem2);
      JMenu editMenu = new JMenu("Edit");
      editMenu.setMnemonic(KeyEvent.VK_E);
      menuBar.add(editMenu);
      frame.setJMenuBar(menuBar);
      frame.setSize(550, 350);
      frame.setVisible(true);
   }
}

Output


Updated on: 30-Jul-2019

130 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements