Saturday, August 24, 2013

JMenu

JMenu represents a menu that contains menuitems. Menus (created by JMenu class) are added to a menu bar object (created by JMenuBar class) by using the add(JMenu menu) method of the menu bar object. MenuItems (created by JMenuItem class) are added to a menu object by using the add(JMenuItem item) method of the menu object. When a menu of the menu bar is selected, menuitems of the menu are displayed.

A menu or menuitem can associate with an action through its constructor or by using its setAction(Action action) method. A direct class that implements the Action interface is AbstractAction. You can extends the AbstractAction class to determine the properties (text and icons) and actions of the menus or menuitems.

Constructors of the JMenu class:
-JMenu()
creates a menu without text.
-JMenu(String text)
creates a menu with text.
-JMenu(Action action)
creates a menu with its properties and action defined by Action object.

Useful methods of the JMenu class:
-add(Action item):JMenuItem
adds an menu item that its properties and action are specified by the Action object to the menu.
-add(JMenuItem item):JMenuItem
adds a menu item to the menu.
-addSeparator():void
separates the menu items of the menu.
-insert(JMenuItem,int post):void
inserts a menu item to the menu at the specified position.

Example:

import java.awt.BorderLayout;
import java.awt.Container;
import java.awt.event.ActionEvent;
import java.awt.event.KeyEvent;
import javax.swing.AbstractAction;
import javax.swing.Icon;
import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.JMenu;
class JMenuShow extends JFrame{
JMenuShow(String title){
setTitle(title);
setSize(500,200);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
Container contpane=getContentPane();
contpane.setLayout(new BorderLayout());
setVisible(true);
JMenuBar mbar=new JMenuBar();
JMenu mfile=new JMenu("File");
mfile.setMnemonic(KeyEvent.VK_F);
JMenuItem item0=new JMenuItem("New");
mfile.add(item0);
JMenu item1=new JMenu(new AAction("Window"));
JMenuItem subitem0=new JMenuItem(new AAction("Close",new ImageIcon("d:/closeicon.png")));
JMenuItem subitem1=new JMenuItem(new AAction("Minimize",new ImageIcon("d:/minicon.png")));
item1.add(subitem0);
item1.add(subitem1);
mfile.add(item1);
mbar.add(mfile);
   setJMenuBar(mbar);
   validate();
}


class AAction extends AbstractAction{

AAction(String text){
super(text);

}
AAction(String text,Icon c){
super(text, c);

}
public void actionPerformed(ActionEvent e){
if(e.getActionCommand().equals("Close"))
System.exit(0);
else if(e.getActionCommand().equals("Minimize"))
setExtendedState(JFrame.ICONIFIED);
}
}


}

public class JFrameSwing {
public static void main(String[] args){
new JMenuShow("JMenu");
}
}

JMenu JMenuBar

No comments:

Post a Comment