Wednesday 20 May 2015

Filled Under:

Tutorial On JMenu Bar With ActionListener

As we see in many java applications menubar is used to perform specific task specific task can be performed by applying action Listener in menubar. Before applying action Listener  in a menu bar I  recommend you read this tutorial first  How to create simple j menu bar in java  because first you  should know how to create simple menubar .In This program I am using action performed method to perform exit   for just explaining how to use this method.If you want to perform some another function using menubar remove dispose() from program  then add your code at that place.

CODING:

import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
class myjframe1 extends JFrame implements ActionListener
{

JMenuBar menuBar = new JMenuBar();
JMenu firstmenu = new JMenu();
JMenuItem exit = new JMenuItem();
public myjframe1() 

{
super();
setTitle("Menu Bar Example");
setSize(300, 200);
setVisible(true);
setDefaultCloseOperation(EXIT_ON_CLOSE);        
setJMenuBar(menuBar);
menuBar.add(firstmenu);
firstmenu.setText("First Menu");
firstmenu.add(exit);
exit.setText("  Exit  ");
exit.addActionListener(this);
}

public void actionPerformed(ActionEvent e) 
{
if (e.getSource() == exit)
dispose();
}
}
class men
{
public static void main(String args[])
{
myjframe1 x= new myjframe1();
}
}


OUTPUT:


0 comments:

Post a Comment