Creating Menu Based Application using Swing in Java

Creating Menu Based Application using Swing in Java

beginning with programming logo

Table of Contents

a) Introduction
b) Example with Source Code
c) Output

*************

Introduction

To create menu based application using swing in java, we need swing components like JMenuBar, JMenu, JMenuItem. These all components are in javax.swing packages. From the below image you will be able to know about the menu bar , menu and menu items.
menu based application


Let us see the source code and output of the program. In this program the main class is MenuBasedAppUsingSwingDemo and I have created the JMenuBar , JMenu and JMenuItem for the application. All the necessary information regarding the program is written in the comments in source code.

Source Code:


/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package MenuBasedAppUsingSwing;

/**
 *
 * @author AnkitPC
 */
import javax.swing.*; //for components
import java.awt.*; //for layout
public class MenuBasedAppUsingSwingDemo {
    JFrame f;
    JMenuBar mb;
    JMenu m1,m2;
    JMenuItem mi1,mi2,mi3,mi4;
   
    //constructor
    MenuBasedAppUsingSwingDemo(){
        f=new JFrame("Menu Based Application Demo");
        f.setSize(400,300);
        f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        //set layout
        f.setLayout(new FlowLayout());
       
        mb=new JMenuBar();
        //adding menu bar to frame
        f.setJMenuBar(mb);
            
        m1=new JMenu("File");
        m2=new JMenu("Application");
       
        mi1=new JMenuItem("new");
        mi2=new JMenuItem("Exit");
       
        mi3=new JMenuItem("Run");
        mi4=new JMenuItem("Play");
       
        // adding menus to menu bar
        mb.add(m1);
        mb.add(m2);
       
        // adding menu items for menu m1
        m1.add(mi1);
        m1.add(mi2);
        // adding menu items for menu m2
        m2.add(mi3);
        m2.add(mi4);
       

        f.setVisible(true);
    }
   
    //main method
    public static void main(String[] args) {
        //calling constructor
        new MenuBasedAppUsingSwingDemo();
    }
   
}

Output:

menu based application output

menu based application output



Now, I think some of you are going to add the menu bar to the frame like this f.add(mb). If you write the code like this f.add(mb)instead of f.setJMenuBar(mb) then you will get this output.

Output:

menu based application output

menu based application output

**************************

Previous Lessons;
JTable in Java

Post a Comment

0 Comments