This is a Java Program to Create a Menu with Several Menu Items
We have to write a program in Java such that it creates a menu bar with menu items and the the label of the menu item is displayed in the frame.
For creating a menu with several items, we can have the following sets of input and output.
1.To View the Menu:
When the program is being executed, it is expected that the frame consists of the menu.
2.To Select a Menu Item:
When any menu item is selected from the menu bar, it is expected that the label of the menu item selected is displayed.
1. Create a menu and add menu items to it.
2. Add ActionListener to all menu items.
3. Create a menu bar and add the menu to it.
4. Create a label and display the menu item selected.
Here is source code of the Java Program to view the label of item selected from a Menu. The program is successfully compiled and tested using javac compiler on Fedora 30. The program output is also shown below.
/*Java Program to Create a Menu and Display the Menu Item Selected*/
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
class Menu implements ActionListener
{
static JLabel text;
//Driver function
public static void main(String args[])
{
//Create a frame
JFrame frame = new JFrame("Menu");
frame.setSize(500,500);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLayout(new FlowLayout());
//Create an object
Menu obj = new Menu();
//Create a Menu
JMenu menu = new JMenu("Select Here");
//Create Menu Items
JMenuItem item[] = new JMenuItem[5];
for(int i=0;i<5;i++)
{
item[i]=new JMenuItem("Item "+(i+1));
item[i].addActionListener(obj);
menu.add(item[i]);
}
//Create a menu bar
JMenuBar mb=new JMenuBar();
mb.add(menu);
frame.setJMenuBar(mb);
//Create the label
text = new JLabel();
frame.add(text);
//Display the frame
frame.setVisible(true);
}
//Function to display the menu item selected
public void actionPerformed(ActionEvent e)
{
text.setText("Menu Item Selected : "+e.getActionCommand());
}
}
1. Create a menu using JMenu class.
2. To create menu items use the JMenuItem class.
3. Create a menu bar using JMenuBar and add the menu to it.
4. Set the menu to the frame using setJMenuBar function.
5. Display the label of the menu item selected.
Here’s the run time test cases for selecting an item from a menu.
Test case 1 – To View the Menu.
Test case 2 – To View the Menu Item Selected.
Test case 3 – To View the Menu Item Selected.
Sanfoundry Global Education & Learning Series – Java Programs.
If you find any mistake above, kindly email to [email protected]- Check Programming Books
- Practice Information Technology MCQs
- Practice BCA MCQs
- Practice Programming MCQs
- Check Java Books