JMenuItem - Easy Logic to create multiple Menu Items

Well, today is a post of a simple and easy logic that helps to create multiple menu items without no extra steps. You can also write actions for this, but it might be lengthy. Whatsoever, i have not used actions in this demo, you can take a look at it.




import javax.swing.*;
import java.awt.*;
class JMenuItemsDemo extends JFrame
{
JMenuBar mbar;
JMenu menu;
public JMenuItemsDemo()
{
setTitle("JMenuItem Demo");
setSize(400,400);
setDefaultCloseOperation(EXIT_ON_CLOSE);
setVisible(true);


// Create menubar
mbar=new JMenuBar();


// Create menu
menu=new JMenu("File");


// Menu Item list
String list="New Open Save SaveAs Print Exit";


// Split items with space
String[] menuitems=list.split(" ");

for(int i=0;i<menuitems.length;i++)
{
JMenuItem item=new JMenuItem(menuitems[i]);
item.setMnemonic(menuitems[i].charAt(0));
menu.add(item);
}


// Add menu to menubar
mbar.add(menu);


// Set JMenuBar to frame
setJMenuBar(mbar);
}

public static void main(String args[])
{
new JMenuItemsDemo();
}
}
String list: Contains the list of names that are to be displayed on the menu items each separated with a space.

list.split(" "): Splits the string (here list) separated by a space. For example "Gowtham Gutha" gets splitted into two strings i.e. Gowtham and Gutha. This method is in java.lang.String class. After all the words are splitted, it returns a string array of the words. As i've said just now, in "Gowtham Gutha" two words are returned in the form of a string array.

For loop: The for loop contains the code to add menu items to the menu.

JMenuItem list=new JMenuItem(menuitems[i]): The call to this constructor creates a JMenuItem object with a name.
For example, menuitems[0] means New
menuitems[1] means Open and so on.

list.setMnemonic(menuitems[i].charAt(0)): This sets the mnemonic, (you can observe an underlined word in each menu item). This method takes a character as parameter. Here, i menuitems[i].charAt(0) means the first letter of the menu item's name.

For example, menuitems[0].charAt(0) is equal to 'N'
menuitems[0].charAt(0) is equal to 'O'

menu.add(item): Adds the menu item (that was created/customized in the above two steps) to the menu.