Java Swing GUI

How to Create a Vertical Menu Bar in Java Swing

In this tutorial, we are going to see how to create a Vertical menu bar in Java Swing. If you want a vertical menu bar, simply change the LayoutManager of the menu bar component.


Let’s create a menu bar first:

JMenuBar menuBar = new JMenuBar();

Now define its layout to create a vertical menu bar with GridLayout:

menuBar.setLayout(new GridLayout(0,1));

The following example creates a vertical menu bar in Java.
 

 

Java Program to Create a Vertical Menu Bar:
import java.awt.GridLayout;
import java.awt.event.KeyEvent;
import javax.swing.*;

public class VerticalMenu 
{
   public static void main(final String args[]) 
   {
      //create a frame 
      JFrame frame = new JFrame("Vertical Menu");
      //create a menu
      JMenuBar menu = new JMenuBar();
      //set menu layout
      menu.setLayout(new GridLayout(0,1));
    
      //create menu items
      JMenu file = new JMenu("File");
      menu.add(file);
    
      //create the submenu
      JMenuItem newf = new JMenuItem("New");
      file.add(newf);
    
      JMenuItem open = new JMenuItem("Open");
      file.add(open);
    
      JMenu edit = new JMenu("Edit");
      menu.add(edit);
    
      JMenu help = new JMenu("Help");
      menu.add(help);
      menu.revalidate();
    
      //add menu to frame
      frame.setJMenuBar(menu);
      frame.setSize(300, 250);
      frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
      frame.setVisible(true);
   }
}

Output:


mcqMCQPractice competitive and technical Multiple Choice Questions and Answers (MCQs) with simple and logical explanations to prepare for tests and interviews.Read More

Leave a Reply

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