Download Laboratory Session 5: Creating a Menu

Survey
yes no Was this document useful for you?
   Thank you for your participation!

* Your assessment is very important for improving the workof artificial intelligence, which forms the content of this project

Document related concepts
no text concepts found
Transcript
Laboratory Session 5: Creating a Menu
A menu bar is one of the most visible parts of the GUI application. It is a group of commands
located in various menus. In Java Swing, to implement a menu bar, we use three objects. A
JMenuBar, a JMenu and a JMenuItem.
Step 1: Run Netbeans and if you are not placed back in your project simply open it. Move to
the projects tab and right mouse click on the project name, from the pop-up menu select New
and from the next pop-up menu select Java Class. You will be presented with a New Java
Class form, edit the form to:
Class Name:
Project:
Location:
Package:
Create File:
Menu
HCIProject (Should already be set)
Source Package (Should already be set)
Should already be set
Should already be set
Click finish and you should be placed back into the editor.
Step 2: Edit Menu.java to:
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;
public class Menu extends JFrame {
public Menu()
{
setTitle("JMenuBar");
JMenuBar menubar = new JMenuBar();
JMenu file = new JMenu("File");
JMenuItem fileClose = new JMenuItem("Close");
fileClose.setToolTipText("Exit application");
fileClose.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent event) {
System.exit(0);
}
});
menubar.add(file);
setJMenuBar(menubar);
file.add(fileClose);
setVisible(true);
setSize(320,260);
setLocationRelativeTo(null);
}
public static void main(String[] args) {
Menu men = new Menu();
men.setVisible(true);
}
}
Step 6: Run your application and you will see the following output.
Explanation:
In the above example there is a menu with one item. Selecting the close menu item we close
the application.
JMenuBar menubar = new JMenuBar();
Here we create a menubar.
JMenu file = new JMenu("File");
We create a menu object. The menus can be accessed via the keybord as well. To bind a
menu to a particular key.
fileClose.setToolTipText("Exit application");
This code line creates a tooltip for a menu item.