Create Menu bar on the frame by using java

In this program, we will learn how to create a menu bar on the frame in Java Swing. JMenuBar is the class that is mandatory for the menu bar. The swing package is also important for the menu bar. If we want to create menu items on the menu bar its possible with the JMenuItem class. One or more menu items we create on one menu.

First, we create a frame and set the size. Now we create a menu bar with JMenuBar and set the bounds. After this, we add menu items on the menu bar.

Create Menu Bar in Java Swing

Let’s create a menu bar on the frame.

import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.io.*;

class MenuTest implements ActionListener
{
  JFrame fr;
  JMenuBar bar;
  JMenu m,n;
  JMenuItem m1,m2,m3,n1,n2,n3;
  JTextArea ta;
  JFileChooser jf;
MenuTest()

{
  fr=new JFrame();
  fr.setSize(400,400);
  fr.setLayout(null);
  
  ta=new JTextArea();
  ta.setBounds(0,0,fr.getWidth(),fr.getHeight());
  fr.add(ta);
  
  bar=new JMenuBar();
  fr.setJMenuBar(bar);
  
  m=new JMenu("Color");
  m.setMnemonic(KeyEvent.VK_R);
    n= new JMenu("File");
  bar.add(m);
  bar.add(n);
  
  m1=new JMenuItem("Red");
  m.add(m1);
     m2=new JMenuItem("Green");
   m.add(m2);
    m3=new JMenuItem("Yellow");
  m.add(m3);
  
  n1=new JMenuItem("open");
  n2=new JMenuItem("save");
  n3=new JMenuItem("print");
  n.add(n1);
  n.add(n2);
  n.add(n3);
  fr.setVisible(true);
}
public static void main(String s[])
  {
    new MenuTest();
  }
}

In this program first, we import the swing package after that we declared the variables. After we set the size of the frame and set the bounds of the menu bar. After that, we add the menu items on the menu bar with JMenuItem.

The output of the program

create a menu bar on the frame in Java swing

Output: Menu bar in Swing – Java

Read more,





Leave a Reply

Your email address will not be published. Required fields are marked *