Java Graphical User Interface(GUI): JMenuBar, JMenu and JMenuItem functions and operations using Eclipse IDE

in #utopian-io7 years ago (edited)

What Will I Learn?

  • The user will learn the concept behind the Swing Construct called JMenuBar
  • The user will learn the concept behind the Swing Construct called JMenu
  • The user will learn the concept behind the Swing Construct called JMenuItem
  • The user will learn how to create a Simple Notepad with functions using these objects.

Requirements

  • A computer System is required for this tutorial.
  • Java Software Development Kit(JDK) must be installed on your computer.
  • An Integrated Development Environment(IDE) such as Eclipse or NetBeans is required to be installed on your computer.

Get JDK here

Get Eclipse here

Get NetBeans here

Difficulty

Intermediate.

Tutorial Contents

This tutorial introduces three Swing constructs which can be used to serve one purpose.

JMenuBar

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

public class JMenuBar extends JComponent implements MenuElement, Accessible

JMenu class declaration

public class JMenu extends JMenuItem implements MenuElement, Accessible

JMenuItem class declaration

public class JMenuItem extends AbstractButton implements Accessible, MenuElement

JMenu

The Menu class represents the pull-down menu component which is deployed from a menu bar.
It is an implementation of a menu -- a popup window containing JMenuItems that is displayed when the user selects an item on the JMenuBar. In addition to JMenuItems, a JMenu can also contain JSeparators.
In essence, a menu is a button with an associated JPopupMenu. When the "button" is pressed, the JPopupMenu appears. If the "button" is on the JMenuBar, the menu is a top-level window. If the "button" is another menu item, then the JPopupMenu is "pull-right" menu.
Menus can be configured, and to some degree controlled, by Actions. Using an Action with a menu has many benefits beyond directly configuring a menu.

JMenuItem

An implementation of an item in a menu. A menu item is essentially a button sitting in a list. When the user selects the "button", the action associated with the menu item is performed. A JMenuItem contained in a JPopupMenu performs exactly that function.
Menu items can be configured, and to some degree controlled, by Actions. Using an Action with a menu item has many benefits beyond directly configuring a menu item.

In this tutorial, we will create two classes;

  • Class 1: We will create these three objects and also a JTextArea object. The text area will serve as a text editor with a menu bar at the top. The menu bar will contain options and when clicked, menu items will drop down. These items will be associated with actions using ActionListener interface.

  • Class 2: Contains main method for run instructions.

This tutorial is done in assumption that the user follows through previous tutorials and is familiar with the coding terms used therein, also, have basic Java programming knowledge.

IMPORTANT NOTE

If you follow previous tutorials, you will notice these Swing Constructs are created the same way, however, their functionalities differ.
You may use the same line of code to create objects of these constructs, but making them function requires different methods of coding.
This is where this tutorial comes in handy. The tutorial uses an example to illustrate its functions and actions that can be associated with it.

1.png
2.png

3.png

4.png
5.png

CODE BLOCK

Menu Class
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class Menu extends JFrame {
    private JTextArea textArea;
    private JMenuBar menuBar;
    private JMenu fontMenu;
    private JMenu colorMenu;
    private JMenu sizeMenu;
    private JMenuItem fontMenuItem1;
    private JMenuItem fontMenuItem2;
    private JMenuItem fontMenuItem3;
    private JMenuItem colorMenuItem1;
    private JMenuItem colorMenuItem2;
    private JMenuItem colorMenuItem3;
    private JMenuItem colorMenuItem4;
    private JMenuItem colorMenuItem5;
    private JMenuItem colorMenuItem6;
    private JMenuItem help;
    public Menu() {
        super("JMenuBar Demo");
        textArea = new JTextArea();
        add(new JScrollPane(textArea), BorderLayout.CENTER);
        menuBar = new JMenuBar();
        add(menuBar, BorderLayout.NORTH);
        fontMenu = new JMenu("Font");
        menuBar.add(fontMenu);
        fontMenuItem1 = new JMenuItem("Bold");
        fontMenuItem1.addActionListener(
                new ActionListener() {
                    public void actionPerformed(ActionEvent event) {
                        textArea.setFont(new Font("Serif", Font.PLAIN, 22));
                    }
                }
                );
        fontMenuItem2 = new JMenuItem("Italic");
        fontMenuItem2.addActionListener(
                new ActionListener() {
                    public void actionPerformed(ActionEvent event) {
                        textArea.setFont(new Font("Serif", Font.ITALIC, 22));
                    }
                }
                );
        fontMenuItem3 = new JMenuItem("Roman Baseline");
        fontMenuItem3.addActionListener(
                new ActionListener() {
                    public void actionPerformed(ActionEvent event) {
                        textArea.setFont(new Font("Serif", Font.ROMAN_BASELINE, 22));
                    }
                }
                );
        fontMenu.add(fontMenuItem1);
        fontMenu.add(fontMenuItem2);
        fontMenu.add(fontMenuItem3);
        
        colorMenu = new JMenu("Color");
        menuBar.add(colorMenu);
        
        colorMenuItem1 = new JMenuItem("Red");
        colorMenuItem1.addActionListener(
                new ActionListener() {
                    public void actionPerformed(ActionEvent event) {
                        textArea.setForeground(Color.RED);
                    }
                }
                );
        colorMenuItem2 = new JMenuItem("Blue");
        colorMenuItem2.addActionListener(
                new ActionListener() {
                    public void actionPerformed(ActionEvent event) {
                        textArea.setForeground(Color.BLUE);
                    }
                }
                );
        colorMenuItem3 = new JMenuItem("Green");
        colorMenuItem3.addActionListener(
                new ActionListener() {
                    public void actionPerformed(ActionEvent event) {
                        textArea.setForeground(Color.GREEN);
                    }
                }
                );
        colorMenuItem4 = new JMenuItem("Orange");
        colorMenuItem4.addActionListener(
                new ActionListener() {
                    public void actionPerformed(ActionEvent event) {
                        textArea.setForeground(Color.ORANGE);
                    }
                }
                );
        colorMenuItem5 = new JMenuItem("Cyan");
        colorMenuItem5.addActionListener(
                new ActionListener() {
                    public void actionPerformed(ActionEvent event) {
                        textArea.setForeground(Color.CYAN);
                    }
                }
                );
        colorMenuItem6 = new JMenuItem("Pink");
        colorMenuItem6.addActionListener(
                new ActionListener() {
                    public void actionPerformed(ActionEvent event) {
                        textArea.setForeground(Color.PINK);
                    }
                }
                );
        colorMenu.add(colorMenuItem1);
        colorMenu.add(colorMenuItem2);
        colorMenu.add(colorMenuItem3);
        colorMenu.add(colorMenuItem4);
        colorMenu.add(colorMenuItem5);
        colorMenu.add(colorMenuItem6);
        sizeMenu = new JMenu("About");
        menuBar.add(sizeMenu);
        help = new JMenuItem("Help");
        help.addActionListener(
                new ActionListener() {
                    public void actionPerformed(ActionEvent event) {
                        textArea.getSelectedTextColor();
                        textArea.setText("Type text in Text Area, Click Font"
                                + " to select and change font, click Color to select "
                                + " and change color of text.");
                    }
                }
                );
        sizeMenu.add(help); 
    }
}
menuMain Class
import javax.swing.JFrame;
public class menuMain {
    public static void main (String args []) {
        Menu bar = new Menu();
        bar.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        bar.setSize(500, 300);
        bar.setVisible(true);
    }
}

Output

ezgif.com-optimize.gif

Menu Class

menuBar = new JMenuBar();
add(menuBar, BorderLayout.NORTH);
        
fontMenu = new JMenu("Font");
menuBar.add(fontMenu);

The code above creates the JMenuBar object, which is a bar at the top of the frame and adds it to the frame.

The JMenu object is also created. This is a clickable option on the Menu Bar. It is then added to the menu bar by using menuBar.add() method.

fontMenuItem1 = new JMenuItem("Bold");
fontMenuItem1.addActionListener(
new ActionListener() {
public void actionPerformed(ActionEvent event) {
textArea.setFont(new Font("Serif", Font. BOLD, 22));
}
}
);

A MenuItem object with the tag “Bold” is created ; this item will drop down when the “font” menu is clicked.
An ActionListener interface is used to associate events to this object.
The actionPerformed method in the ActionListener interface is also implemented.
The font of the text in the text area becomes bold and font size is changed to 22.

fontMenuItem2 = new JMenuItem("Italic");
fontMenuItem2.addActionListener(
new ActionListener() {
public void actionPerformed(ActionEvent event) {
textArea.setFont(new Font("Serif", Font.ITALIC, 22));
}
}
);

A second MenuItem object with the tag “Italic” is created ; this item will drop down when the “font” menu is clicked.
An ActionListener interface is used to associate events to this object.
The actionPerformed method in the ActionListener interface is also implemented.
The font of the text in the text area becomes Italic and font size is changed to 22.

fontMenuItem3 = new JMenuItem("Roman Baseline");
fontMenuItem3.addActionListener(
new ActionListener() {
public void actionPerformed(ActionEvent event) {
textArea.setFont(new Font("Serif", Font.ROMAN_BASELINE, 22));
}
}
);

A third MenuItem object with the tag “Roman Baseline” is created; this item will drop down when the “font” menu is clicked.
An ActionListener interface is used to associate events to this object.
The actionPerformed method in the ActionListener interface is also implemented.
The font of the text in the text area changes to Roman Baseline and font size is changed to 22.

fontMenu.add(fontMenuItem1);
fontMenu.add(fontMenuItem2);
fontMenu.add(fontMenuItem3);

The three created MenuItems are then added to the Menu objects using the .add method.

colorMenu = new JMenu("Color");
menuBar.add(colorMenu);

A second Menu object named “Color” is created and added to the screen.

colorMenuItem1 = new JMenuItem("Red");
colorMenuItem1.addActionListener(
new ActionListener() {
public void actionPerformed(ActionEvent event) {
textArea.setForeground(Color.RED);
}
}
);

A MenuItem object with the tag “Red” is created; this item will drop down when the “Color” menu is clicked.
An ActionListener interface is used to associate events to this object.
The actionPerformed method in the ActionListener interface is also implemented.
The ``` .setForeground() is used to change the color of the text in the text area to Red.

colorMenuItem2 = new JMenuItem("Blue");
colorMenuItem2.addActionListener(
new ActionListener() {
public void actionPerformed(ActionEvent event) {
textArea.setForeground(Color.BLUE);
}
}
);
colorMenuItem3 = new JMenuItem("Green");
colorMenuItem3.addActionListener(
new ActionListener() {
public void actionPerformed(ActionEvent event) {
textArea.setForeground(Color.GREEN);
}
}
);
colorMenuItem4 = new JMenuItem("Orange");
colorMenuItem4.addActionListener(
new ActionListener() {
public void actionPerformed(ActionEvent event) {
textArea.setForeground(Color.ORANGE);
}
}
);
colorMenuItem5 = new JMenuItem("Cyan");
colorMenuItem5.addActionListener(
new ActionListener() {
public void actionPerformed(ActionEvent event) {
textArea.setForeground(Color.CYAN);
}
}
);
colorMenuItem6 = new JMenuItem("Pink");
colorMenuItem6.addActionListener(
new ActionListener() {
public void actionPerformed(ActionEvent event) {
textArea.setForeground(Color.PINK);
}
}
);

Five more MenuItem objects are created with tags “Blue”, “Green”, “Orange”, “Cyan”, and “Pink”.

ActionListener interface is used to associate events to these objects.
The actionPerformed method in the ActionListener interface is also implemented in all the objects.
The ``` .setForeground() is used to change the color of the text in the text area. Depending on the object selected, the color changes to that object.

colorMenu.add(colorMenuItem1);
colorMenu.add(colorMenuItem2);
colorMenu.add(colorMenuItem3);
colorMenu.add(colorMenuItem4);
colorMenu.add(colorMenuItem5);
colorMenu.add(colorMenuItem6);

The MenuItems are then added to the Menu using the .add() method.

aboutMenu = new JMenu("About");
menuBar.add(aboutMenu);

A third JMenu item named “About” is created and added to the MenuBar using the .add() method.

help = new JMenuItem("Help");
help.addActionListener(
new ActionListener() {
public void actionPerformed(ActionEvent event) {
textArea.setText("Type text in Text Area, Click Font"
+ " to select and change font, click Color to select "
+ " and change color of text.");
}
}
);

One MenuItem object with the tag “Help” is created; this item will drop down when the “About” menu is clicked.
An ActionListener interface is used to associate events to this object.
The actionPerformed method in the ActionListener interface is also implemented.
The .setText() method is used to set the text of the text area.

menuMain class

import javax.swing.JFrame;

public class menuMain {
public static void main (String args []) {
Menu bar = new Menu();
bar.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
bar.setSize(500, 300);
bar.setVisible(true);
}
}

Main class containing main method with instructions on how the program runs.

An object of the Slider class is created. The slider class holds instructions for running the program.

The program Exit Mode is set. This will close the program when user clicks the “X” button on the frame.

Size of the window is set using inbuilt methods .setSize

Visibility setting is set, making the frame visible, the code .setVisible(true) is used.

ezgif.com-optimize.gif

The program is run and the output simulates a basic notepad-like environment for text editing.
Options are located on the MenuBar and when clicked, a list of MenuItems appear.
When any of the Items is clicked, an event occurs and an action is associated with the text typed in the text area.

You can get the codes at my GitHub Account if you want to try it on your own.

REFERENCES

Curriculum

Similar posts already posted on Utopian are:



Posted on Utopian.io - Rewarding Open Source Contributors

Sort:  

Thank you for the contribution. It has been approved.

You can contact us on Discord.
[utopian-moderator]

Hey @creon, I just gave you a tip for your hard work on moderation. Upvote this comment to support the utopian moderators and increase your future rewards!

Hey @will-ugo I am @utopian-io. I have just upvoted you!

Achievements

  • You have less than 500 followers. Just gave you a gift to help you succeed!
  • Seems like you contribute quite often. AMAZING!

Community-Driven Witness!

I am the first and only Steem Community-Driven Witness. Participate on Discord. Lets GROW TOGETHER!

mooncryption-utopian-witness-gif

Up-vote this comment to grow my power and help Open Source contributions like this one. Want to chat? Join me on Discord https://discord.gg/Pc8HG9x

Congratulations! This post has been upvoted from the communal account, @minnowsupport, by will-ugo from the Minnow Support Project. It's a witness project run by aggroed, ausbitbank, teamsteem, theprophet0, someguy123, neoxian, followbtcnews, and netuoso. The goal is to help Steemit grow by supporting Minnows. Please find us at the Peace, Abundance, and Liberty Network (PALnet) Discord Channel. It's a completely public and open space to all members of the Steemit community who voluntarily choose to be there.

If you would like to delegate to the Minnow Support Project you can do so by clicking on the following links: 50SP, 100SP, 250SP, 500SP, 1000SP, 5000SP.
Be sure to leave at least 50SP undelegated on your account.

Coin Marketplace

STEEM 0.20
TRX 0.25
JST 0.038
BTC 97445.74
ETH 3477.06
USDT 1.00
SBD 3.16