Java Swing Menu example implements ActionListener program

By | August 16, 2011

You can find here code for Java Swing Menu example implements ActionListener program. You can find the details about required components and classes to create Menu.

In this article you will learn about how to create a menu with action in Java Swing. In general MenuBar contains collection of menus and each menu we can have number of menu items. We can add some action for each menu items to perform some action.

JMenuBar is a class which construct menu bar and we can have number of menus in that. JMenu is a class which is having number of constructor. JMenu(String) is one constriction. In string place we can give our menu name to display in window. We can use JMenuItem(String) consctuctor to add number of menu items in each menu. The following program will help you to develop Java Swing Menu progarm.

Program:
import java.awt.Container;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.JFrame;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.JOptionPane;

public class SwingMenuwithAction extends JFrame implements ActionListener {
JFrame frame1;
JMenu menu1;
JMenuBar menuBar;
JMenuItem menuItem1;
JOptionPane jop1;

public SwingMenuwithAction(){
frame1=new JFrame(“Welcome to Deena Project”);
Container cp=frame1.getContentPane();
cp.setLayout(null);
menuBar=new JMenuBar();

menu1=new JMenu(“File”);
menu1.setMnemonic(‘F’); //optional
menu1.add(menuItem1=new JMenuItem(“Open”));
menuItem1.addActionListener(this);
menuBar.add(menu1);
frame1.setJMenuBar(menuBar);
frame1.setSize(300,200);
frame1.setVisible(true);
}

public void actionPerformed(ActionEvent ae)
{
if(ae.getSource()==menuItem1)
{
jop1=new JOptionPane();
jop1.showMessageDialog(frame1,”You have clicked the Menu Item Open”);
}
}

public static void main(String[] args) {
new SwingMenuwithAction();
}

}

You need to save this program using SwingMenuwithAction.java name. Then complie using javac filename and run using java filename to get output.

Leave a Reply

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