We can also develop an application with a Menu. As a name indicates a Menu consists of Menu objects.
Menus
We can also develop an application with a Menu.
As a name indicates a Menu consists of Menu objects. These Menu objects
comprise of MenuItem objects which can be selected by the user with a
click of a mouse. A MenuItem may be a String, checkbox, separator,
menu etc.
Following are the steps to to add menus to any Frame:
- You need to create a MenuBar first with the
help of the following method.
MenuBar mb = new MenuBar();
2. Then
you need to create a Menu using Menu m = new Menu("File");.
3. Now the
MenuItem options can be added to the Menu from top to bottom,
using the following methods.
mi.add(new MenuItem("Open"));
mi.add(new
CheckboxMenuItem("Type here"));
4. Now you can
add the Menu to the MenuBar from left to right using mi.add(m);.
5. Finally, you need
to add the MenuBar to the Frame by calling the setMenuBar() method.
The program code given below, creates an application window with a menu bar.
import java.awt.*;
import java.awt.event.*;
public class MainWindow extends Frame {
public MainWindow() {
super("Menu Window");
setSize(400, 400);
FileMenu fileMenu = new FileMenu(this);
HelpMenu helpMenu = new HelpMenu(this);
MenuBar mb = new MenuBar();
mb.add(fileMenu);
mb.add(helpMenu);
setMenuBar(mb);
addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
exit();
}
});
}
public void exit() {
setVisible(false);
dispose();
System.exit(0);
}
public static void main(String args[]) {
MainWindow w = new MainWindow();
w.setVisible(true);
}
}
class FileMenu extends Menu implements ActionListener {
MainWindow mw;
public FileMenu(MainWindow m) {
super("File");
mw = m;
MenuItem mi;
add(mi = new MenuItem("Open"));
mi.addActionListener(this);
add(mi = new MenuItem("Close"));
mi.addActionListener(this);
add(mi = new MenuItem("Exit"));
mi.addActionListener(this);
}
public void actionPerformed(ActionEvent e) {
String item = e.getActionCommand();
if (item.equals("Exit"))
mw.exit();
else
System.out.println("Selected FileMenu " + item);
}
}
class HelpMenu extends Menu implements ActionListener {
MainWindow mw;
public HelpMenu(MainWindow m) {
super("Help");
mw = m;
MenuItem mi;
add(mi = new MenuItem("Basics"));
mi.addActionListener(this);
add(mi = new MenuItem("Advanced"));
mi.addActionListener(this);
addSeparator();
add(mi = new CheckboxMenuItem("Manual"));
mi.addActionListener(this);
Menu subMenu = new Menu("Miscellaneous");
subMenu.add(mi = new MenuItem("Help"));
mi.addActionListener(this);
subMenu.add(mi = new MenuItem("Other Option"));
mi.addActionListener(this);
add(subMenu);
}
public void actionPerformed(ActionEvent e) {
String item = e.getActionCommand();
if (item.equals("Basics"))
System.out.println("Basics");
else if (item.equals("Help"))
System.out.println("Help");
}
}
|
|
Output of the program:
C:\newprgrm>javac MainWindow.java
C:\newprgrm>java MainWindow |
Download this example.