In this tutorial, we are going to create a simple Swing JMenu.
Swing JMenu Example :
MenuDemo.java
package com.swing.examples;
import javax.swing.*;
import java.awt.Container;
import java.awt.BorderLayout;
public class MenuDemo extends JFrame {
JMenu normalMenu, radioMenu, checkMenu;
JMenuItem new1, open;
JRadioButtonMenuItem radio1, radio2;
JCheckBoxMenuItem check1, check2;
JMenuBar mainMenu;
Container ContentPane;
ButtonGroup group;
MenuDemo() {
super("JMenu Demo");
normalMenu = new JMenu("Normal Menu");
radioMenu = new JMenu("Radio Menu");
checkMenu = new JMenu("Check Menu");
new1 = new JMenuItem("New...", new ImageIcon(
"C:\\Desktop\\images\\new.gif"));
open = new JMenuItem("Open...", new ImageIcon(
"C:\\Desktop\\images\\open.gif"));
normalMenu.add(new1);
normalMenu.add(open);
radio1 = new JRadioButtonMenuItem("First Radio Option");
radio2 = new JRadioButtonMenuItem("Second Radio Option");
group = new ButtonGroup();
group.add(radio1);
group.add(radio2);
radioMenu.add(radio1);
radioMenu.add(radio2);
check1 = new JCheckBoxMenuItem("First Check Option");
check2 = new JCheckBoxMenuItem("Second Check Option");
checkMenu.add(check1);
checkMenu.add(check2);
mainMenu = new JMenuBar();
mainMenu.add(normalMenu);
mainMenu.add(radioMenu);
mainMenu.add(checkMenu);
ContentPane = getContentPane();
ContentPane.add(mainMenu, BorderLayout.NORTH);
setSize(400, 275);
setVisible(true);
}
public static void main(String[] args) {
new MenuDemo();
}
}
Output :
JMenu with Images :JMenu with Check Boxes:
JMenu with Radio Buttons:
Happy Learning 🙂