JMenu Example

This example shows how to construct menus in Java. The main Menu “File” contains three subitems. Each item can be accessed by a mouse click or by its keyboard mnemonic. Once a subitem is clicked a message is displayed explaining wich subitem was clicked.


import javax.swing.*;
import java.awt.event.*;
public class Menu extends JFrame{
public Menu()
{
super("Menu example");

JMenu file = new JMenu("File");
file.setMnemonic('F');
JMenuItem newItem = new JMenuItem("New");
newItem.setMnemonic('N');
file.add(newItem);
JMenuItem openItem = new JMenuItem("Open");
openItem.setMnemonic('O');
file.add(openItem);
JMenuItem exitItem = new JMenuItem("Exit");
exitItem.setMnemonic('x');
file.add(exitItem);

//adding action listener to menu items
newItem.addActionListener(
new ActionListener(){
public void actionPerformed(ActionEvent e)
{
System.out.println("New is pressed");
}
}
);
openItem.addActionListener(
new ActionListener(){
public void actionPerformed(ActionEvent e)
{
System.out.println("Open is pressed");
}
}
);
exitItem.addActionListener(
new ActionListener(){
public void actionPerformed(ActionEvent e)
{
System.out.println("Exit is pressed");
}
}
);
JMenuBar bar = new JMenuBar();
setJMenuBar(bar);
bar.add(file);

getContentPane();
setSize(200, 200);
setVisible(true);
}

public static void main(String[] args)
{
Menu app = new Menu();
app.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s