Professional Documents
Culture Documents
Lecture-3.1.7
Lecture-3.1.7
Lecture-3.1.7
DEPARTMENT : CSE
Bachelor of Engineering (Computer Science & Engineering)
Java Programming (20CST-218)
TOPIC OF PRESENTATION:
2
Java Swing Example
JMenuBar, JMenu and JMenuItems are a part of Java Swing package. JMenuBar is
an implementation of menu bar . the JMenuBar contains one or more JMenu
objects, when the JMenu objects are selected they display a popup showing one or
more JMenuItems.
6
// create a frame
// add menu items to menu
static JFrame f;
x.add(m1);
public static void main() x.add(m2);
{ x.add(m3);
// create a frame
f = new JFrame("Menu demo"); // add menu to menu bar
// create a menubar mb.add(x);
mb = new JMenuBar();
// create a menu // add menubar to frame
x = new JMenu("Menu"); f.setJMenuBar(mb);
// create menuitems
m1 = new JMenuItem("MenuItem1"); // set the size of the frame
f.setSize(500, 500);
m2 = new JMenuItem("MenuItem2");
f.setVisible(true);
m3 = new JMenuItem("MenuItem3"); }
}
7
Output
8
2. Program to add a menubar and add menuitems, submenu items and also add ActionListener to
menu items
// Java program Program to add a menubar
// and add menuitems, submenu items and also add
// ActionListener to menu items
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
public class menu1 extends JFrame implements ActionListener {
// menubar
static JMenuBar mb;
// JMenu
static JMenu x, x1;
// Menu items
static JMenuItem m1, m2, m3, s1, s2;
9
// create a frame
static JFrame f; // create a menu
// a label x = new JMenu("Menu");
static JLabel l; x1 = new JMenu("submenu");
// main class // create menuitems
public static void main() m1 = new JMenuItem("MenuItem1");
{ m2 = new JMenuItem("MenuItem2");
// create an object of the class m3 = new JMenuItem("MenuItem3");
menu1 m = new menu1(); s1 = new JMenuItem("SubMenuItem1");
// create a frame s2 = new JMenuItem("SubMenuItem2");
f = new JFrame("Menu demo"); // add ActionListener to menuItems
// create a label m1.addActionListener(m);
l = new JLabel("no task "); m2.addActionListener(m);
// create a menubar m3.addActionListener(m);
mb = new JMenuBar(); s1.addActionListener(m);
s2.addActionListener(m);
10
// add menu items to menu
x.add(m1); // add label
x.add(m2); f.add(l);
x.add(m3); // set the size of the frame
x1.add(s1); f.setSize(500, 500);
x1.add(s2); f.setVisible(true);
// add submenu }
x.add(x1); public void actionPerformed(ActionEvent e)
// add menu to menu bar {
mb.add(x); String s = e.getActionCommand();
// add menubar to frame // set the label to the menuItem that is selected
f.setJMenuBar(mb); l.setText(s + " selected");
}
}
11
Summary:
Video Lectures :
https://youtu.be/FY3g4gGPhio
Reference Links:
https://www.geeksforgeeks.org/java-swing-jmenubar/?ref=rp
http://zetcode.com/javaswing/basicswingcomponents/
https://www.geeksforgeeks.org/java-swing-jpanel-examples/
https://www.javatpoint.com/java-swing
https://www.guru99.com/java-swing-gui.html
THANK YOU