Wednesday, April 27, 2016

Adding a Menu with sub menus in Swing

In this blog post I am going to show you how to add the below JMenuBar to a JFrame in a Swing application.









Below is the commented code for the application. I will explain how to add ActionListeners to these menu items once clicked in another post separately.

 import javax.swing.*;  
 import java.awt.*;  
 public class MenuBarExampleMain extends JFrame{  
   public MenuBarExampleMain(){  
  //sets the title for the JFrame  
     super("Menu Bar Example App");             
     this.createInterface();  
   }  
   public void createInterface(){  
  //main Layout of the JFrame is BorderLayout  
     setLayout(new BorderLayout());             
     Toolkit tk = Toolkit.getDefaultToolkit();  
     int xSize = ((int) tk.getScreenSize().getWidth());  
     int ySize = ((int) tk.getScreenSize().getHeight());  
  //setting the JFrame size according to the screen width and height  
     setSize(xSize,ySize);                  
     JPanel mainPanel = new JPanel(new BorderLayout());  
  //creating a JMenuBar and adding it on top of the frame  
     mainPanel.add(createMenuBar(),BorderLayout.NORTH);   
     add(mainPanel, BorderLayout.CENTER);  
     setVisible(true);  
   }  
   public JMenuBar createMenuBar(){  
     JMenuBar menuBar=new JMenuBar();  
  //File,Edit,View and Help are the main menus in the JMenuBar  
     JMenu menuFile=new JMenu("File");            
     JMenu menuEdit=new JMenu("Edit");  
     JMenu menuView=new JMenu("View");  
     JMenu menuHelp=new JMenu("Help");  
  //Open and Exit are the sub menu items under 'File' menu item  
     JMenuItem subMenuItemOpen=new JMenuItem("Open");    
     JMenuItem subMenuItemExit=new JMenuItem("Exit");  
     menuFile.add(subMenuItemOpen);  
     menuFile.add(subMenuItemExit);  
     menuBar.add(menuFile);  
     menuBar.add(menuEdit);  
     menuBar.add(menuView);  
     menuBar.add(menuHelp);  
     return menuBar;  
   }  
   public static void main(String[] args){  
     MenuBarExampleMain main=new MenuBarExampleMain();  
   }  
 }