How to remove menus from MenuBar in Java?

Java 8Object Oriented ProgrammingProgramming

Remove a menu from the MenuBar using the remove() method. Set the index for the menu you want to remove from the MenuBar.

Let’s say we have the following two menus initially −

The following is an example to remove one the above menus. Let’s say we are removing the 2nd menus “Edit” −

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);
      JMenuItem menuItem3 = new JMenuItem("Cut", KeyEvent.VK_C);
      editMenu.add(menuItem3);
      menuBar.remove(1);
      menuBar.revalidate();
      frame.setJMenuBar(menuBar);
      frame.setSize(550, 350);
      frame.setVisible(true);
   }
}

Output

raja
Updated on 30-Jul-2019 22:30:26

Advertisements