Monday, November 22, 2010

How to create a menu bar and add a menu separator in java swing with eclipse

As we know java swing provides more liveliness to a web page, we can create menu bar using simple steps in java swing, which helps user to do his/her operations quickly.With out menu the task will be more tedious and very complex, so every one needs to menu bar  in web page. Now lets start with a simple swing program, as by program you can get it more quickly and easily.
To start a Java  program in Eclipse see here

//Java swing menu bar program starts

import javax.swing.*;
import java.awt.event.KeyEvent;
public class SwingMenu extends JFrame{
public SwingMenu(){
JMenuBar menubar=new JMenuBar();

ImageIcon openicon=new ImageIcon("open.png");
   
JMenu file=new JMenu("File");
file.setMnemonic(KeyEvent.VK_F);

JMenuItem open=new JMenuItem("open",openicon);
open.setMnemonic(KeyEvent.VK_O);

JMenuItem close=new JMenuItem("Close");
close.setMnemonic(KeyEvent.VK_C);

JMenu edit=new JMenu("Edit");
edit.setMnemonic(KeyEvent.VK_E); 

//adding menu item to menu
file.add(open);
file.add(close);

//addin menus to menubar
menubar.add(file);
menubar.add(edit);

setVisible(true);
setSize(205,250);
setJMenuBar(menubar);
setDefaultCloseOperation(EXIT_ON_CLOSE);
}

public static void main(String kl[]){
SwingUtilities.invokeLater(new Runnable(){
public void run(){
new SwingMenu();
}
});
}
}

Compile the program in Eclipse 

Output screen:
 










As it is clear that JMenuBar is used for menu bar, JMenu for menu, and JMenuItem for menu item and at the last step I added all Menu items to menu and menu to menu bar.

What this is used for?

ImageIcon openicon=new ImageIcon("open.png");
This is usesd for image displayed in the menu item.



edit.setMnemonic(KeyEvent.VK_E);
this code is used for shortcut. If you press alt+e edit menu will open.



How to create a separator menu in java
?
Lets say that import is the separator menu that you want to add.Have a look at the below code statement you will get.

JMenu imp=new JMenu("imp");
imp.setMnemonic(KeyEvent.VK_I);
Create the menu first.after that.Add the menu item list that you want to add to the import.

JMenuItem impfile=new JMenuItem("import file");
JMenuItem imimg=new JMenuItem("imp image");

In the above code I added import file and import image menu item you can try any thing.
After that add this menu items to import.See here how I did.

imp.add(impfile);
imp.add(imimg);

Add you are in the last step, just add this code for separator menu

file.addSeparator();
file.add(imp);
file.addSeparator();

And very thing is the same as the above sample code.

Now lets look at the output screen.

click to view

1 comment: