Below is the simple source code to implement JMenu, JMenuItem and JMenuBar.
Source Code
import java.awt.event.ActionEvent;
import java.io.IOException;
import javax.swing.JFrame;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import java.awt.event.ActionListener;
import javax.swing.JOptionPane;
public class ExploreMenu implements ActionListener {
ExploreMenu() {
JFrame frame = new JFrame("Explore Menu");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(300,300);
frame.setResizable(false);
frame.setLocationRelativeTo(null);
// Create the menu bar
JMenuBar menuBar = new JMenuBar();
// Create a menu
JMenu menu = new JMenu("File");
menuBar.add(menu);
// Create a menu item
JMenuItem item = new JMenuItem("Windows");
menu.add(item);
// Install the menu bar in the frame
frame.setJMenuBar(menuBar);
frame.setVisible(true);
item.addActionListener(this);
}
public void actionPerformed(ActionEvent ae) {
if(ae.getActionCommand().equals("Windows")) {
try {
Runtime.getRuntime().exec("explorer C:\\WINDOWS");
}catch(IOException ie){
ie.printStackTrace();
} catch(Exception e) {
e.printStackTrace();
}
}
}
public static void main(String[] args) {
ExploreMenu exploreMenu = new ExploreMenu();
}
import java.io.IOException;
import javax.swing.JFrame;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import java.awt.event.ActionListener;
import javax.swing.JOptionPane;
public class ExploreMenu implements ActionListener {
ExploreMenu() {
JFrame frame = new JFrame("Explore Menu");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(300,300);
frame.setResizable(false);
frame.setLocationRelativeTo(null);
// Create the menu bar
JMenuBar menuBar = new JMenuBar();
// Create a menu
JMenu menu = new JMenu("File");
menuBar.add(menu);
// Create a menu item
JMenuItem item = new JMenuItem("Windows");
menu.add(item);
// Install the menu bar in the frame
frame.setJMenuBar(menuBar);
frame.setVisible(true);
item.addActionListener(this);
}
public void actionPerformed(ActionEvent ae) {
if(ae.getActionCommand().equals("Windows")) {
try {
Runtime.getRuntime().exec("explorer C:\\WINDOWS");
}catch(IOException ie){
ie.printStackTrace();
} catch(Exception e) {
e.printStackTrace();
}
}
}
public static void main(String[] args) {
ExploreMenu exploreMenu = new ExploreMenu();
}
}
No comments:
Post a Comment