从JMenu调用JFrame选项窗格

时间:2013-05-09 06:04:44

标签: java swing jframe jmenu

... JMenuDemo

import java.awt.BorderLayout;
import java.awt.Container;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import java.awt.event.KeyEvent;
import javax.swing.ImageIcon;
import javax.swing.JCheckBoxMenuItem;
import javax.swing.JFrame;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.JPanel;
import javax.swing.JRadioButtonMenuItem;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.KeyStroke;


public class JMenuDemo implements ActionListener, ItemListener {

    JTextArea jtAreaOutput;
    JScrollPane jspPane;

    public JMenuBar createJMenuBar() {
        JMenuBar mainMenuBar;
        JMenu menu1, menu2, menu3, submenu;
        JMenuItem plainTextMenuItem, textIconMenuItem, iconMenuItem, subMenuItem;
        JRadioButtonMenuItem rbMenuItem;
        JCheckBoxMenuItem cbMenuItem;
        ImageIcon icon = createImageIcon("jmenu.jpg");
        mainMenuBar = new JMenuBar();
        menu1 = new JMenu("File");
        menu1.setMnemonic(KeyEvent.VK_M);
        mainMenuBar.add(menu1);
        // Creating the MenuItems
        plainTextMenuItem = new JMenuItem("New",
                        KeyEvent.VK_T);
        // can be done either way for assigning shortcuts
        // menuItem.setMnemonic(KeyEvent.VK_T);
        // Accelerators, offer keyboard shortcuts to bypass navigating the menu
        // hierarchy.
        plainTextMenuItem.setAccelerator(KeyStroke.getKeyStroke(
                        KeyEvent.VK_1, ActionEvent.ALT_MASK));
        plainTextMenuItem.addActionListener(this);
        menu1.add(plainTextMenuItem);
        textIconMenuItem = new JMenuItem("Open",
                        icon);
        textIconMenuItem.setMnemonic(KeyEvent.VK_B);
        textIconMenuItem.addActionListener(this);
        menu1.add(textIconMenuItem);
        // Menu Item with just an Image
        iconMenuItem = new JMenuItem(icon);
        iconMenuItem.setMnemonic(KeyEvent.VK_D);
        iconMenuItem.addActionListener(this);
        //menu1.add(iconMenuItem);
        menu1.addSeparator();
        // Radio Button Menu items follow a seperator
        //ButtonGroup itemGroup = new ButtonGroup();

        textIconMenuItem = new JMenuItem("Records", icon);
        textIconMenuItem.setMnemonic(KeyEvent.VK_B);
        textIconMenuItem.addActionListener(this);
        menu1.add(textIconMenuItem);
        // Menu Item with just an Image
        iconMenuItem = new JMenuItem(icon);
        iconMenuItem.setMnemonic(KeyEvent.VK_D);
        iconMenuItem.addActionListener(this);
        //menu1.add(iconMenuItem);

        textIconMenuItem = new JMenuItem("Recent Records", icon);
        textIconMenuItem.setMnemonic(KeyEvent.VK_C);
        textIconMenuItem.addActionListener(this);
        menu1.add(textIconMenuItem);
        // Menu Item with just an Image
        iconMenuItem = new JMenuItem(icon);
        iconMenuItem.setMnemonic(KeyEvent.VK_E);
        iconMenuItem.addActionListener(this);
        //menu1.add(iconMenuItem);

        //        "Menu Item with Radio Button");
        //rbMenuItem.setSelected(true);
        //rbMenuItem.setMnemonic(KeyEvent.VK_R);
        //itemGroup.add(rbMenuItem);
        //rbMenuItem.addActionListener(this);
        //menu1.add(rbMenuItem);
        //rbMenuItem = new JRadioButtonMenuItem(
        //        "Menu Item 2 with Radio Button");
        //itemGroup.add(rbMenuItem);
        //    rbMenuItem.addActionListener(this);
        //    menu1.add(rbMenuItem);
        menu1.addSeparator();
        textIconMenuItem = new JMenuItem("Passenger Profile", icon);
        textIconMenuItem.setMnemonic(KeyEvent.VK_D);
        textIconMenuItem.addActionListener(this);
        menu1.add(textIconMenuItem);
        // Menu Item with just an Image
        iconMenuItem = new JMenuItem(icon);
        iconMenuItem.setMnemonic(KeyEvent.VK_F);
        iconMenuItem.addActionListener(this);
        //menu1.add(iconMenuItem);
        // Radio Button Menu items follow a seperator
        //cbMenuItem = new JCheckBoxMenuItem("Menu Item with check box");
        //cbMenuItem.setMnemonic(KeyEvent.VK_C);
        //cbMenuItem.addItemListener(this);
        //menu1.add(cbMenuItem);
        //cbMenuItem = new JCheckBoxMenuItem("Menu Item 2 with check box");
        //cbMenuItem.addItemListener(this);
        //menu1.add(cbMenuItem);
        textIconMenuItem = new JMenuItem("Services", icon);
        textIconMenuItem.setMnemonic(KeyEvent.VK_E);
        textIconMenuItem.addActionListener(this);
        menu1.add(textIconMenuItem);
        // Menu Item with just an Image
        iconMenuItem = new JMenuItem(icon);
        iconMenuItem.setMnemonic(KeyEvent.VK_G);
        iconMenuItem.addActionListener(this);
        //menu1.add(iconMenuItem);
        // Sub Menu follows a seperator
        menu1.addSeparator();
        //submenu = new JMenu("Sub Menu");
        //submenu.setMnemonic(KeyEvent.VK_S);
        //subMenuItem = new JMenuItem("Sub MenuItem 1");
        //subMenuItem.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_2,
        //    ActionEvent.CTRL_MASK));
        //subMenuItem.addActionListener(this);
        //submenu.add(subMenuItem);
        //subMenuItem = new JMenuItem("Sub MenuItem 2");
        //submenu.add(subMenuItem);
        //subMenuItem.addActionListener(this);
        //menu1.add(submenu);
        // Build second menu in the menu bar.
        textIconMenuItem = new JMenuItem("Exit", icon);
        textIconMenuItem.setMnemonic(KeyEvent.VK_F);
        textIconMenuItem.addActionListener(this);
        menu1.add(textIconMenuItem);
        // Menu Item with just an Image
        iconMenuItem = new JMenuItem(icon);
        iconMenuItem.setMnemonic(KeyEvent.VK_H);
        iconMenuItem.addActionListener(this);
        menu2 = new JMenu("Menu 2");
        menu2.setMnemonic(KeyEvent.VK_N);
        mainMenuBar.add(menu2);
        return mainMenuBar;
    }

    public Container createContentPane() {
        // Create the content-pane-to-be.
        JPanel jplContentPane = new JPanel(new BorderLayout());
        jplContentPane.setLayout(new BorderLayout());// Can do it either way
        // to set layout
        jplContentPane.setOpaque(true);
        // Create a scrolled text area.
        jtAreaOutput = new JTextArea(5, 30);
        jtAreaOutput.setEditable(false);
        jspPane = new JScrollPane(jtAreaOutput);
        // Add the text area to the content pane.
        jplContentPane.add(jspPane, BorderLayout.CENTER);
        return jplContentPane;
    }

    /**
     * Returns an ImageIcon, or null if the path was invalid.
     */
    protected static ImageIcon createImageIcon(String path) {
        java.net.URL imgURL = JMenuDemo.class.getResource(path);
        if (imgURL != null) {
            return new ImageIcon(imgURL);
        } else {
            System.err.println("Couldn't find image file: " + path);
            return null;
        }
    }

    private static void createGUI() {
        JFrame.setDefaultLookAndFeelDecorated(true);
        // Create and set up the window.
        JFrame frame = new JFrame("JG Book & Fly");
        //    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        JMenuDemo app = new JMenuDemo();
        frame.setJMenuBar(app.createJMenuBar());
        frame.setContentPane(app.createContentPane());
        frame.setSize(1200, 700);
        frame.setVisible(true);
    }

    public void actionPerformed(ActionEvent e) {
        JMenuItem source = (JMenuItem) (e.getSource());
        String s = "Menu Item source: " + source.getText()
                        + " (an instance of " + getClassName(source) + ")";
        jtAreaOutput.append(s + "\n");
        jtAreaOutput.setCaretPosition(jtAreaOutput.getDocument()
                        .getLength());
        String name = source.getActionCommand();
        if (name.equalsIgnoreCase("exit")) {
            System.exit(0);
        }

    }

    public void itemStateChanged(ItemEvent e) {
        JMenuItem source = (JMenuItem) (e.getSource());
        String s = "Menu Item source: "
                        + source.getText()
                        + " (an instance of "
                        + getClassName(source)
                        + ")"
                        + "\n"
                        + "    State of check Box: "
                        + ((e.getStateChange() == ItemEvent.SELECTED) ? "selected"
                        : "unselected");
        jtAreaOutput.append(s + "\n");
        jtAreaOutput.setCaretPosition(jtAreaOutput.getDocument()
                        .getLength());
    }
    // Returns the class name, no package info

    protected String getClassName(Object o) {
        String classString = o.getClass().getName();
        int dotIndex = classString.lastIndexOf(".");
        return classString.substring(dotIndex + 1); // Returns only Class name
    }

    public static void main(String[] args) {
        javax.swing.SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                createGUI();
            }
        });
    }
}

... JOptionPaneDemo

import java.awt.Container;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.util.StringTokenizer;
import javax.swing.AbstractButton;
import javax.swing.ButtonGroup;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JRadioButton;


public class JOptionPaneDemo extends JFrame implements ActionListener {

    Container contentPane = null;
    private JButton jbnDialog;
    String ButtonLabels;
    private JRadioButton[] dialogTypeButtons;
    private JRadioButton[] messageTypeButtons;
    private int[] messageTypes = {JOptionPane.PLAIN_MESSAGE,
        JOptionPane.INFORMATION_MESSAGE, JOptionPane.QUESTION_MESSAGE,
        JOptionPane.WARNING_MESSAGE, JOptionPane.ERROR_MESSAGE};
    private ButtonGroup messageTypeButtonGroup, buttonTypeButtonGroup,
                    dialogTypeButtonGroup;
    private JRadioButton[] optionTypeButtons;
    private int[] OptionTypes = {JOptionPane.DEFAULT_OPTION,
        JOptionPane.YES_NO_OPTION, JOptionPane.YES_NO_CANCEL_OPTION,
        JOptionPane.OK_CANCEL_OPTION};

    public static void main(String[] args) {
        new JOptionPaneDemo();
    }

    public JOptionPaneDemo() {
        super("JOptionPane Source Demo");
        addWindowListener(new WindowListener());
        contentPane = getContentPane();
        contentPane.setLayout(new GridLayout(0, 1));
        JPanel jplButton = new JPanel();
        jbnDialog = new JButton("Show an Option Pane");
        jbnDialog.addActionListener(this);
        jplButton.add(jbnDialog);
        contentPane.add(jplButton);
        createRadioButtonGroupings();
        ButtonLabels = "Button1 Button2 Button3";
        pack();
        setSize(1400, 700);
        setVisible(true);
    }

    public void createRadioButtonGroupings() {
        JPanel jplDialogType = new JPanel();
        dialogTypeButtonGroup = new ButtonGroup();
        dialogTypeButtons = new JRadioButton[]{
            new JRadioButton("Show Message", true),
            new JRadioButton("Get Confirmation"),
            new JRadioButton("Collect Input"),
            new JRadioButton("Present Options")};
        for (int i = 0; i < dialogTypeButtons.length; i++) {
            dialogTypeButtonGroup.add(dialogTypeButtons[i]);
            jplDialogType.add(dialogTypeButtons[i]);
        }
        contentPane.add(jplDialogType);
        JPanel jplMessageType = new JPanel();
        messageTypeButtonGroup = new ButtonGroup();
        messageTypeButtons = new JRadioButton[]{
            new JRadioButton("Plain"),
            new JRadioButton("Information", true),
            new JRadioButton("Question"), new JRadioButton("Warning"),
            new JRadioButton("Error")};
        for (int i = 0; i < messageTypeButtons.length; i++) {
            messageTypeButtonGroup.add(messageTypeButtons[i]);
            jplMessageType.add(messageTypeButtons[i]);
        }
        contentPane.add(jplMessageType);
        JPanel jplButtonType = new JPanel();
        buttonTypeButtonGroup = new ButtonGroup();
        optionTypeButtons = new JRadioButton[]{
            new JRadioButton("Default", true),
            new JRadioButton("Yes/No"),
            new JRadioButton("Yes/No/Cancel"),
            new JRadioButton("OK/Cancel")};
        for (int i = 0; i < optionTypeButtons.length; i++) {
            buttonTypeButtonGroup.add(optionTypeButtons[i]);
            jplButtonType.add(optionTypeButtons[i]);
        }
        contentPane.add(jplButtonType);
    }
    // Windows Listener for Window Closing

    public class WindowListener extends WindowAdapter {

        public void windowClosing(WindowEvent event) {
            System.exit(0);
        }
    }

    public void actionPerformed(ActionEvent event) {
        /*
         * dialogTypeButtons =
         *
         * new JRadioButton[] { new JRadioButton("Show Message", true),
         *
         * new JRadioButton("Get Confirmation"),
         *
         * new JRadioButton("Collect Input"),
         *
         * new JRadioButton("Present Options") };
         */
        if (dialogTypeButtons[0].isSelected()) {
            JOptionPane.showMessageDialog(this, "Show Message",
                            "Simple Dialog", getMessageType());
        } else if (dialogTypeButtons[1].isSelected()) {
            JOptionPane.showConfirmDialog(this, "Get Confirmation",
                            "Simple Dialog", getButtonType(), getMessageType());
        } else if (dialogTypeButtons[2].isSelected()) {
            JOptionPane.showInputDialog(this, "Collect Input",
                            "Simple Dialog", getMessageType(), null, null, null);
        } else if (dialogTypeButtons[3].isSelected()) {
            JOptionPane.showOptionDialog(this, "Present Options",
                            "Simple Dialog", getButtonType(), getMessageType(),
                            null, substrings(ButtonLabels), null);
        }
    }

    private int getAssociatedType(AbstractButton[] buttons, int[] types) {
        for (int i = 0; i < buttons.length; i++) {
            if (buttons[i].isSelected()) {
                return (types[i]);
            }
        }
        return (types[0]);
    }

    private int getMessageType() {
        return (getAssociatedType(messageTypeButtons, messageTypes));
    }

    private int getButtonType() {
        return (getAssociatedType(optionTypeButtons, OptionTypes));
    }

    private String[] substrings(String string) {
        StringTokenizer tok = new StringTokenizer(string);
        String[] substrings = new String[tok.countTokens()];
        for (int i = 0; i < substrings.length; i++) {
            substrings[i] = tok.nextToken();
        }
        return (substrings);
    }
}

上面是两个不同的第一个是JMenu,另一个是JFrame。我想通过点击new ...

中的JMenu来调用第二个“选项”窗格

1 个答案:

答案 0 :(得分:1)

分开您的顾虑,即对菜单项使用单独的操作。 只需在plainTextMenuItem中添加一个action或actionlistener,然后调用new JOptionPaneDemo();

plainTextMenuItem.addActionListener(new ActionListener(){
       @Override
       public void actionPerformed(ActionEvent e){
              new JOptionPaneDemo();
       }
});