public class MenuDemoGUIApp1 extends JFrame
1: //MenuDemoGUIApp1.java
2: //Illustrates menus and an image button.
4: import javax.swing.*;
5: import java.awt.event.*;
6: import java.awt.*;
8: public class MenuDemoGUIApp1 extends JFrame
9: implements ActionListener
10: {
11: JMenuBar wholeMenuBar;
12: JMenu fileMenu, editMenu;
13: JMenuItem openItem, saveItem, copyItem, pasteItem;
14: JButton quitButton, cancelButton;
15: Container c;
17: public MenuDemoGUIApp1()
18: {
19: c = getContentPane();
20: c.setLayout(new FlowLayout());
21: wholeMenuBar = new JMenuBar();
22: setJMenuBar(wholeMenuBar);
24: //File menu, with Open and Save options
25: fileMenu = new JMenu("File");
26: openItem = new JMenuItem("Open");
27: fileMenu.add(openItem);
28: openItem.addActionListener(this);
29: saveItem = new JMenuItem("Save");
30: fileMenu.add(saveItem);
31: saveItem.addActionListener(this);
32: wholeMenuBar.add(fileMenu);
34: //Edit menu, with Copy and Paste options
35: editMenu = new JMenu("Edit");
36: copyItem = new JMenuItem("Copy");
37: editMenu.add(copyItem);
38: copyItem.addActionListener(this);
39: pasteItem = new JMenuItem("Paste");
40: editMenu.add(pasteItem);
41: pasteItem.addActionListener(this);
42: wholeMenuBar.add(editMenu);
44: //Create an image button
45: Icon ovalIcon = new ImageIcon("cancel.gif");
46: cancelButton = new JButton(ovalIcon);
47: c.add(cancelButton);
48: cancelButton.addActionListener(this);
50: quitButton = new JButton("Quit");
51: c.add(quitButton);
52: quitButton.addActionListener(this);
53: }
55:
56: public void actionPerformed(ActionEvent e)
57: {
58: if (e.getSource() == openItem)
59: {
60: JFileChooser fileChooser = new JFileChooser();
61: int userResponse = fileChooser.showOpenDialog(this);
62: if (userResponse == JFileChooser.CANCEL_OPTION)
63: JOptionPane.showMessageDialog(null, "User cancelled.");
64: else
65: JOptionPane.showMessageDialog(null, "User chose" +
66: fileChooser.getSelectedFile());
67: }
69: if (e.getSource() == saveItem)
70: JOptionPane.showMessageDialog(null, "Save chosen.");
71: if (e.getSource() == copyItem)
72: JOptionPane.showMessageDialog(null, "Copy chosen.");
73: if (e.getSource() == pasteItem)
74: JOptionPane.showMessageDialog(null, "Paste chosen.");
75: if (e.getSource() == cancelButton)
76: JOptionPane.showMessageDialog(null, "OK ... who am " +
77: "I to argue?");
78: if(e.getSource() == quitButton)
79: System.exit(0);
80: }
83: public static void main(String args[])
84: {
85: MenuDemoGUIApp1 app = new MenuDemoGUIApp1();
86: app.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
87: app.setSize(200, 200);
88: app.show();
89: }
90: }