Java

Creating JMenu in java using Netbeans with Examples

Menus in java

Creating JMenu in java using Netbeans- Applications rarely do without menu bars or context menus (the menu that is opened with the right mouse button). With the complexity of a program, the need for menus usually increases. They are, so to speak, the application’s signpost that guides the user through the program. The following table gives a brief overview of the classes, which we will deal with in this article, and a short description of the respective purpose.


Java menu Classes:

Class short description
JMenuItem A JMenuItem represents a menu item (entry in a menu), eg “Open file” or “Exit”.
JMenu The JMenu is a container for JMenuItems to which any number of JMenuItems can be added. “File” in the menu bar of your browser or word processor would be an example of a JMenu. 
JMenuBar The JMenuBar is the entire menu bar of a window.  It can contain any number of JMenus.
JCheckBoxMenuItem A JCheckBoxMenuItem is similar to the   JMenuItem,  but with the addition of a check box. When you click, the tick is set or removed. For example, JCheckBoxMenuItems are often used to activate or deactivate window contents.
JRadioButtonMenuItem Similar to the JCheckBoxMenuItem, radio buttons are used here. There are usually at least two   JRadioButtonMenuItem s representing the options to choose between.
JPopupMenu The JPopupMenu is the so-called context menu, which appears when you click the right mouse button.
JSeperator The separator is used to separate the menu items. 



JMenuBar in java:

In Java, menu bars are implemented using the javax.swing.JMenuBar class. JMenuBar objects serve as containers for each menu bar item.

Example: how to create a simple menu bar using jMenubar in java:

First, we create an object of our class JDialog. We could also use a JFrame, this doesn’t matter for a menu bar. We then give our dialog box title ” menu creating Example.” Since menu items will only be explained in the following section, we will leave them out here for the time being. In order to still make the menu bar visible, we provide it with a simple red border. We create an object of the LineBorder class for this and pass the color red to the constructor. Then we create an object of class JMenuBar for our menu bar. Via the setBorder method Let’s associate the border with the menu bar. We then add the menu bar to our dialog and then display it:

Jmenu

In the screenshot, you can see a red stripe at the top. Because our menu bar doesn’t contain any items, it’s only recognizable through our LineBorder object.

The JMenuBar class has a number of methods, but we do not want to list all of them here. The most important is the add method. This method receives an object of the JMenu class as a transfer parameter, which in turn contains a menu structure of individual menu items (JMenuItem).


JMenu in Java

The Java class javax.swing.JMenu serves as a container for the actual menu items.  A  JMenu is, for example, comparable to the “View” menu item, which you can find, for example,  in the top menu bar of various browsers or word processing programs. If you select the “View” menu, you will see the actual menu items, which could be implemented in Java using the JMenuItem class.

Objects of class JMenu can be added to a JMenuBar or a JPopupMenu. The menus can also be nested. For example, if you select the “Toolbars” menu item in the “View” menu in the Firefox browser, another menu opens in which you can again choose between different menu items.

Example: how to create Menu in MenuBar using JMenu in java

As you can see, we simply extended the example from our previous section. Now that we have set our border, we create an object of the JMenu class whose constructor we can pass the title directly to. Then we add the JMenu object to the JMenuBar. If we run the above Java source code, we now get the following dialog:

Jmenu

You can now see from the screenshot above that our border no longer needs to be used to see the JMenuBar , since it now has a menu, which however does not yet have any menu items.

The JMenu class has numerous methods, which we want to give a brief overview of in the following table:

method description
JMenuItem add(JMenuItem menuItem) This method adds an object of class JMenuItem to the JMenu, adding a menu item to the menu.
JMenuItem add(String s) This method creates an object of class  JMenuItem with the name of the supplied string and adds it as a menu item to the calling JMenu object.
void addSeparator() This method adds an object of class  JSeperator as a separator to a JMenu.
JMenuItem insert(JMenuItem mi, int pos) This method adds an object of class  JMenuItem at position pos as a menu item to a JMenu.
void insert(String s, int pos) This method creates an object of class  JMenuItem with the name of the supplied string and adds it as a menu item to the JMenu at position pos.
void insertSeparator(int index) This method adds an object of class  JSeperator as a separator at position pos to a JMenu.
boolean isTopLevelMenu( This method checks whether the JMenu is a direct “child” of a menu bar. This is not possible if this JMenu has been added to a JPopupMenu.
void remove(int pos) This method removes a component at the passed position pos.
void remove(JMenuItem item) This method removes the passed object of class JMenuItem from the JMenu.
void removeAll() This method removes all objects from the  JMenu.
void setMenuLocation(int x, int y) This method sets the position of a popup component to the x and y coordinates.

These methods should be enough to get you started with a menu.


JMenuItem in Java:

The individual menu items of a JMenus are implemented using objects of the javax.swing.JMenuItem class. An example of a menu item is the “Print” entry in the “File” menu of your browser.  

The difference to a JMenu is that when you press a JMenuItem, something usually happens, such as a dialog opening, the program closing, or the view changing. This depends on the action assigned to this menu item.

A JMenuItem can be added to a JMenu or a JPopupMenu .

Now let’s look at some constructors of the JMenuItem class:

constructor description
JMenuItem(String text) The text to be displayed is passed here.
JMenuItem(String text, Icon icon) A text and an icon for the menu item are passed to the constructor. It should be noted here that an icon is not just the path to an icon, but an object of the Icon class that contains the image data.
JMenuItem(String text, int mnemonic) The text to be displayed is passed here and a so-called mnemonic is set. A mnemonic is a key combination that you can also use to select the menu item. For example, in many programs, the “D” is the mnemonic for the “File” menu. So you can open the file menu using the key combination “Alt+D”.
Since mnemonic is an Integer value here, it is the KeyCode of the particular character on the keyboard that you want to use. These can all be found under the KeyEvent class as a constant.



Example: how to create JMenuItem and add it to the JMenu in java:

In the above example, we create an object of the JMenuItem class. For this we use the first constructor of our table JMenuItem(String Text) with the constructors, so we transfer the text of the menu item directly.

If you now run this source code, clicking on the “File” menu will show the entry   JMenuItems new file, save and open file:

Jmenu

How to program a specific action to be performed when a menu item is selected is explained in my next article event handling.

In the following table, we want to give a brief overview of some important methods of the JMenuItem class. Listing and explaining all methods here makes little sense since many methods are rarely used. 

method description
public void addActionListener(ActionListener l) This method was inherited from the  AbstractButton class. Most controls have this method. With an ActionListener, certain events, such as activating the menu item, can be recognized so that the program can react accordingly (eg opening a dialog). There is a more detailed description of events and ActionListeners in the Event Handling article.
public void setText(String text) With this method, the text to be displayed is set. It is also inherited from the  AbstractButton class. This method is also available for many control elements.  This setter method also has a corresponding getter method.
protected void init(String text, Icon icon) This method can be used to initialize the object of the JMenuItem class with a new text and icon.
void setEnabled(boolean b) Many controls also have the setEnabled method. With this method, you can allow the button to be pressed by passing true or block it from all use by passing false.


JCheckBoxMenuItem in java

The JCheckBoxMenuItem class is a child class of the JMenuItem class discussed in the previous section. As the name suggests, it differs from a normal menu item in that the item is preceded by a checkbox. Checkboxes are boxes in which a tick appears or is removed when you click on it. You should be familiar with them from websites and most programs. They are often used when it comes to yes/no questions (e.g. confirmation of general terms and conditions in online shops). You should also already be familiar with menu entries that have a checkbox. In the Firefox browser, for example, you can find them in the menu bar under “View”. You can use the boxes to show or hide the browser’s status bar.

Example: How to add Checkbox in the menu in java using JCheckBoxMenuItem:

After adding a JMenuItem to the JMenu, then I created a JCheckBoxMenuItem and added it to the menu as well. When executing the Java source code, we now get the following picture:

Jmenu

All constructors have been taken over from the superclass JMenuItem. However, there are two additional constructors that can be used to directly set the status of the checkbox when creating the JCheckBoxMenuItem object :

Using the Boolean parameter b, the checkbox can be set with the value true to selected (checkmark present) or with false to deselected (no checkmark).

Appropriate getter and setter methods for the checkbox have also been added. The corresponding status is set with the method void setState(boolean b) and the status of the checkbox is queried with the method boolean getState(). Otherwise, a JCheckBoxMenuItem can be used just like a JMenuItem.



JRadioButtonMenuItem in Java

The JRadioButtonMenuItem class, like JCheckBoxMenuItem, is derived from JMenuItem.

A JRadioButtonMenuItem consists of a radio button and the menu item. A radio button in Java is around a radio button. This is used when the user can choose between several options. Therefore, he usually does not appear alone, but in a so-called group. You have certainly come across the radio button in other applications or on the Internet. In Mozilla Firefox you can find an example of a menu consisting of radio button menu items under View -> Character encoding.

Example: how to add RadioButton into Menu in java using JRadioButtonMenuItem:

When executing the above Java source code, we get the following output:

Jmenu

All constructors have been taken over from the superclass JMenuItem. However, just like with JCheckBoxMenuItem, there are two additional constructors that can be used to directly set the status of the respective radio button:

Using the Boolean parameter selected, the radio button can be set to true with the value selected (circle with a dot) or with false to deselected (circle without a dot).

The JRadioButtonMenuItem class also provides corresponding setter and getter methods: The corresponding status is set using the void setSelected(boolean b) method and the status of the radio button is queried using boolean isSelected(). Otherwise, a JRadioButtonMenuItem can be used in exactly the same way as a JMenuItem.


JSeparator in Java

The Java class javax.swing.JSeparator is used to divide individual menu items or menu groups with a dividing line. Objects of this class, therefore, have no functional meaning, but only help to make the user interface clearer and thus more user-friendly.

In addition to the standard constructor without parameters, JSeparator has another constructor that can be used to specify the alignment of the separating line:

The constants from the interface of the SwingConstants class for horizontal or vertical alignment can be passed as parameters:

If the default constructor is used, the alignment is automatically set to horizontal.


Example: how to use JSeparator in java JMenu:

After we have created the first menu item, we create an object of the JSeparator class. Then we add it to our JMenu. The execution of the Java code gives the following picture:

Jmenu

As you can see after clicking on our menu, a horizontal separator line is now displayed between the JMenuItems.

The setOrientation method can be used to set the separator’s orientation to horizontal or vertical, as in the constructor described above. The associated getter method is called getOrientation and returns the orientation as an Integer value.


JPopupMenu in Java

The context menu, also known as the pop-up menu, is the menu that opens after a right-click. This menu is implemented in Java using the javax.swing.JPopupMenu class. Like JMenuBar, JPopupMenu is a container for menu items and can also hold the same objects.

In addition to the standard constructor, the JPopupMenu class has another one that takes the title for the context menu as a parameter.

We will now add a context menu to the example from the previous section. However, since we haven’t gotten to know event handling yet, we’ll just create a static context menu for illustration purposes. We now create a second object from each menu item, which we add to the JPopupMenu.

After running the above source code, you will get the following output (with the JMenu open):

Jmenu

Since we’ve only implemented a static popup menu here.

Related Articles

Leave a Reply

Your email address will not be published. Required fields are marked *

Back to top button