Skip to main content

Java Swing: JMenuBar, JMenu and JMenuItem, JPopupMenu, JCheckBoxMenuItem

Java JMenuBar, JMenu and JMenuItem

The JMenuBar class is used to display menubar on the window or frame. It may have several menus.

The object of JMenu class is a pull down menu component which is displayed from the menu bar. It inherits the JMenuItem class.

The object of JMenuItem class adds a simple labeled menu item. The items used in a menu must belong to the JMenuItem or any of its subclass.


JMenuBar class declaration

  1. public class JMenuBar extends JComponent implements MenuElement, Accessible  

JMenu class declaration

  1. public class JMenu extends JMenuItem implements MenuElement, Accessible  

JMenuItem class declaration

  1. public class JMenuItem extends AbstractButton implements Accessible, MenuElement  

Java JMenuItem and JMenu Example

  1. import javax.swing.*;  
  2. class MenuExample  
  3. {  
  4.           JMenu menu, submenu;  
  5.           JMenuItem i1, i2, i3, i4, i5;  
  6.           MenuExample(){  
  7.           JFrame f= new JFrame("Menu and MenuItem Example");  
  8.           JMenuBar mb=new JMenuBar();  
  9.           menu=new JMenu("Menu");  
  10.           submenu=new JMenu("Sub Menu");  
  11.           i1=new JMenuItem("Item 1");  
  12.           i2=new JMenuItem("Item 2");  
  13.           i3=new JMenuItem("Item 3");  
  14.           i4=new JMenuItem("Item 4");  
  15.           i5=new JMenuItem("Item 5");  
  16.           menu.add(i1); menu.add(i2); menu.add(i3);  
  17.           submenu.add(i4); submenu.add(i5);  
  18.           menu.add(submenu);  
  19.           mb.add(menu);  
  20.           f.setJMenuBar(mb);  
  21.           f.setSize(400,400);  
  22.           f.setLayout(null);  
  23.           f.setVisible(true);  
  24. }  
  25. public static void main(String args[])  
  26. {  
  27. new MenuExample();  
  28. }}  

Output:

JAVA Jmenuitem and jmenu 1

Example of creating Edit menu for Notepad:

  1. import javax.swing.*;    
  2. import java.awt.event.*;    
  3. public class MenuExample implements ActionListener{    
  4. JFrame f;    
  5. JMenuBar mb;    
  6. JMenu file,edit,help;    
  7. JMenuItem cut,copy,paste,selectAll;    
  8. JTextArea ta;    
  9. MenuExample(){    
  10. f=new JFrame();    
  11. cut=new JMenuItem("cut");    
  12. copy=new JMenuItem("copy");    
  13. paste=new JMenuItem("paste");    
  14. selectAll=new JMenuItem("selectAll");    
  15. cut.addActionListener(this);    
  16. copy.addActionListener(this);    
  17. paste.addActionListener(this);    
  18. selectAll.addActionListener(this);    
  19. mb=new JMenuBar();    
  20. file=new JMenu("File");    
  21. edit=new JMenu("Edit");    
  22. help=new JMenu("Help");     
  23. edit.add(cut);edit.add(copy);edit.add(paste);edit.add(selectAll);    
  24. mb.add(file);mb.add(edit);mb.add(help);    
  25. ta=new JTextArea();    
  26. ta.setBounds(5,5,360,320);    
  27. f.add(mb);f.add(ta);    
  28. f.setJMenuBar(mb);  
  29. f.setLayout(null);    
  30. f.setSize(400,400);    
  31. f.setVisible(true);    
  32. }     
  33. public void actionPerformed(ActionEvent e) {    
  34. if(e.getSource()==cut)    
  35. ta.cut();    
  36. if(e.getSource()==paste)    
  37. ta.paste();    
  38. if(e.getSource()==copy)    
  39. ta.copy();    
  40. if(e.getSource()==selectAll)    
  41. ta.selectAll();    
  42. }     
  43. public static void main(String[] args) {    
  44.     new MenuExample();    
  45. }    
  46. }    

Output:

JAVA Jmenuitem and jmenu 2

Java JPopupMenu

PopupMenu can be dynamically popped up at specific position within a component. It inherits the JComponent class.

JPopupMenu class declaration

Let's see the declaration for javax.swing.JPopupMenu class.

  1. public class JPopupMenu extends JComponent implements Accessible, MenuElement  

Commonly used Constructors:

ConstructorDescription
JPopupMenu()Constructs a JPopupMenu without an "invoker".
JPopupMenu(String label)Constructs a JPopupMenu with the specified title.

Java JPopupMenu Example

  1. import javax.swing.*;  
  2. import java.awt.event.*;  
  3. class PopupMenuExample  
  4. {  
  5.      PopupMenuExample(){  
  6.          final JFrame f= new JFrame("PopupMenu Example");  
  7.          final JPopupMenu popupmenu = new JPopupMenu("Edit");   
  8.          JMenuItem cut = new JMenuItem("Cut");  
  9.          JMenuItem copy = new JMenuItem("Copy");  
  10.          JMenuItem paste = new JMenuItem("Paste");  
  11.          popupmenu.add(cut); popupmenu.add(copy); popupmenu.add(paste);        
  12.          f.addMouseListener(new MouseAdapter() {  
  13.             public void mouseClicked(MouseEvent e) {              
  14.                 popupmenu.show(f , e.getX(), e.getY());  
  15.             }                 
  16.          });  
  17.          f.add(popupmenu);   
  18.          f.setSize(300,300);  
  19.          f.setLayout(null);  
  20.          f.setVisible(true);  
  21.      }  
  22. public static void main(String args[])  
  23. {  
  24.         new PopupMenuExample();  
  25. }}  

Output:

JAVA Jpopmenu 1

Java JPopupMenu Example with MouseListener and ActionListener

  1. import javax.swing.*;  
  2. import java.awt.event.*;  
  3. class PopupMenuExample   
  4. {  
  5.      PopupMenuExample(){  
  6.          final JFrame f= new JFrame("PopupMenu Example");  
  7.          final JLabel label = new JLabel();          
  8.          label.setHorizontalAlignment(JLabel.CENTER);  
  9.          label.setSize(400,100);  
  10.          final JPopupMenu popupmenu = new JPopupMenu("Edit");   
  11.          JMenuItem cut = new JMenuItem("Cut");  
  12.          JMenuItem copy = new JMenuItem("Copy");  
  13.          JMenuItem paste = new JMenuItem("Paste");  
  14.          popupmenu.add(cut); popupmenu.add(copy); popupmenu.add(paste);        
  15.          f.addMouseListener(new MouseAdapter() {  
  16.             public void mouseClicked(MouseEvent e) {              
  17.                 popupmenu.show(f , e.getX(), e.getY());  
  18.             }                 
  19.          });  
  20.         cut.addActionListener(new ActionListener(){  
  21.          public void actionPerformed(ActionEvent e) {              
  22.              label.setText("cut MenuItem clicked.");  
  23.          }  
  24.         });  
  25.         copy.addActionListener(new ActionListener(){  
  26.             public void actionPerformed(ActionEvent e) {              
  27.                 label.setText("copy MenuItem clicked.");  
  28.             }  
  29.            });  
  30.         paste.addActionListener(new ActionListener(){  
  31.             public void actionPerformed(ActionEvent e) {              
  32.                 label.setText("paste MenuItem clicked.");  
  33.             }  
  34.            });  
  35.          f.add(label); f.add(popupmenu);   
  36.          f.setSize(400,400);  
  37.          f.setLayout(null);  
  38.          f.setVisible(true);  
  39.      }  
  40. public static void main(String args[])  
  41. {  
  42.         new PopupMenuExample();  
  43. }  
  44. }  

Output:

JAVA Jpopmenu 2

Java JCheckBoxMenuItem

JCheckBoxMenuItem class represents checkbox which can be included on a menu . A CheckBoxMenuItem can have text or a graphic icon or both, associated with it. MenuItem can be selected or deselected. MenuItems can be configured and controlled by actions.

Nested class

Modifier and TypeClassDescription
protected classJCheckBoxMenuItem.AccessibleJCheckBoxMenuItemThis class implements accessibility support for the JcheckBoxMenuItem class.

Constructor

ConstructorDescription
JCheckBoxMenuItem()It creates an initially unselected check box menu item with no set text or icon.
JCheckBoxMenuItem(Action a)It creates a menu item whose properties are taken from the Action supplied.
JCheckBoxMenuItem(Icon icon)It creates an initially unselected check box menu item with an icon.
JCheckBoxMenuItem(String text)It creates an initially unselected check box menu item with text.
JCheckBoxMenuItem(String text, boolean b)It creates a check box menu item with the specified text and selection state.
JCheckBoxMenuItem(String text, Icon icon)It creates an initially unselected check box menu item with the specified text and icon.
JCheckBoxMenuItem(String text, Icon icon, boolean b)It creates a check box menu item with the specified text, icon, and selection state.

Methods

ModifierMethodDescription
AccessibleContextgetAccessibleContext()It gets the AccessibleContext associated with this JCheckBoxMenuItem.
Object[]getSelectedObjects()It returns an array (length 1) containing the check box menu item label or null if the check box is not selected.
booleangetState()It returns the selected-state of the item.
StringgetUIClassID()It returns the name of the L&F class that renders this component.
protected StringparamString()It returns a string representation of this JCheckBoxMenuItem.
voidsetState(boolean b)It sets the selected-state of the item.

Java JCheckBoxMenuItem Example

  1. import java.awt.event.ActionEvent;  
  2. import java.awt.event.ActionListener;  
  3. import java.awt.event.KeyEvent;  
  4. import javax.swing.AbstractButton;  
  5. import javax.swing.Icon;  
  6. import javax.swing.JCheckBoxMenuItem;  
  7. import javax.swing.JFrame;  
  8. import javax.swing.JMenu;  
  9. import javax.swing.JMenuBar;  
  10. import javax.swing.JMenuItem;  
  11.   
  12. public class JavaCheckBoxMenuItem {  
  13.     public static void main(final String args[]) {  
  14.         JFrame frame = new JFrame("Jmenu Example");  
  15.         frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);  
  16.         JMenuBar menuBar = new JMenuBar();  
  17.         // File Menu, F - Mnemonic  
  18.         JMenu fileMenu = new JMenu("File");  
  19.         fileMenu.setMnemonic(KeyEvent.VK_F);  
  20.         menuBar.add(fileMenu);  
  21.         // File->New, N - Mnemonic  
  22.         JMenuItem menuItem1 = new JMenuItem("Open", KeyEvent.VK_N);  
  23.         fileMenu.add(menuItem1);  
  24.   
  25.         JCheckBoxMenuItem caseMenuItem = new JCheckBoxMenuItem("Option_1");  
  26.         caseMenuItem.setMnemonic(KeyEvent.VK_C);  
  27.         fileMenu.add(caseMenuItem);  
  28.   
  29.         ActionListener aListener = new ActionListener() {  
  30.             public void actionPerformed(ActionEvent event) {  
  31.                 AbstractButton aButton = (AbstractButton) event.getSource();  
  32.                 boolean selected = aButton.getModel().isSelected();  
  33.                 String newLabel;  
  34.                 Icon newIcon;  
  35.                 if (selected) {  
  36.                     newLabel = "Value-1";  
  37.                 } else {  
  38.                     newLabel = "Value-2";  
  39.                 }  
  40.                 aButton.setText(newLabel);  
  41.             }  
  42.         };  
  43.   
  44.         caseMenuItem.addActionListener(aListener);  
  45.         frame.setJMenuBar(menuBar);  
  46.         frame.setSize(350250);  
  47.         frame.setVisible(true);  
  48.     }  
  49. }  

Output:

Java JcheckBoxmenuitem

Anurag Rana Educator CSE/IT

Comments

Popular posts from this blog

JAVA Scrollbar, MenuItem and Menu, PopupMenu

ava AWT Scrollbar The  object  of Scrollbar class is used to add horizontal and vertical scrollbar. Scrollbar is a  GUI  component allows us to see invisible number of rows and columns. AWT Scrollbar class declaration public   class  Scrollbar  extends  Component  implements  Adjustable, Accessible   Java AWT Scrollbar Example import  java.awt.*;   class  ScrollbarExample{   ScrollbarExample(){               Frame f=  new  Frame( "Scrollbar Example" );               Scrollbar s= new  Scrollbar();               s.setBounds( 100 , 100 ,  50 , 100 );               f.add(s);   ...

Difference between net platform and dot net framework...

Difference between net platform and dot net framework... .net platform supports programming languages that are .net compatible. It is the platform using which we can build and develop the applications. .net framework is the engine inside the .net platform which actually compiles and produces the executable code. .net framework contains CLR(Common Language Runtime) and FCL(Framework Class Library) using which it produces the platform independent codes. What is the .NET Framework? The Microsoft .NET Framework is a platform for building, deploying, and running Web Services and applications. It provides a highly productive, standards-based, multi-language environment for integrating existing investments with next-generation applications and services as well as the agility to solve the challenges of deployment and operation of Internet-scale applications. The .NET Framework consists of three main parts: the common language runtime, a hierarchical set of unified class librari...

Standard and Formatted Input / Output in C++

The C++ standard libraries provide an extensive set of input/output capabilities which we will see in subsequent chapters. This chapter will discuss very basic and most common I/O operations required for C++ programming. C++ I/O occurs in streams, which are sequences of bytes. If bytes flow from a device like a keyboard, a disk drive, or a network connection etc. to main memory, this is called   input operation   and if bytes flow from main memory to a device like a display screen, a printer, a disk drive, or a network connection, etc., this is called   output operation . Standard Input and Output in C++ is done through the use of  streams . Streams are generic places to send or receive data. In C++, I/O is done through classes and objects defined in the header file  <iostream> .  iostream  stands for standard input-output stream. This header file contains definitions to objects like  cin ,  cout , etc. /O Library Header Files There are...