如何使JMenu项目在单击时执行某些操作

时间:2012-03-19 22:02:42

标签: java swing user-interface jmenu jmenuitem

我正在制作一个有Jmenu的GUI;它有点击时会做的jmenu项目。那就是问题所在。我看了看,但我找不到如何让它在点击时做点什么。此外,我有点像菜鸟,所以如果你能以一种非常简单的方式做到这一点,那就太棒了!

以下是代码:

import java.awt.Color;
import java.awt.Component;
import javax.swing.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import javax.swing.*;

public abstract class windowMaker extends JFrame implements ActionListener {
private JMenu menuFile;

public static void main(String[] args) {
    createWindow();

}

public static void createWindow() {
    JFrame frame = new JFrame();
    frame.setTitle("*Game Title* Beta 0.0.1");
    frame.setSize(600, 400);
    frame.setLocation(100, 100);
    frame.setVisible(true);
    frame.setResizable(false);
    frame.setDefaultCloseOperation(EXIT_ON_CLOSE);
    frame.setJMenuBar(windowMaker.menuBarCreator());
    frame.add(windowMaker.setTitle());
}

public static void launchURL(String s) {
    String s1 = System.getProperty("os.name");
    try {

        if (s1.startsWith("Windows")) {
            Runtime.getRuntime()
                    .exec((new StringBuilder())
                            .append("rundll32   url.dll,FileProtocolHandler ")
                            .append(s).toString());
        } else {
            String as[] = { "firefox", "opera", "konqueror",   "epiphany",
                    "mozilla", "netscape" };
            String s2 = null;
            for (int i = 0; i < as.length && s2 == null; i++)
                if (Runtime.getRuntime()
                        .exec(new String[] { "which", as[i]   }).waitFor() == 0)
                    s2 = as[i];

            if (s2 == null)
                throw new Exception("Could not find web browser");
            Runtime.getRuntime().exec(new String[] { s2, s });
        }
    } catch (Exception exception) {
        System.out
                .println("An error occured while trying to open the            web browser!\n");
    }
}

public static  JMenuBar menuBarCreator() {
    // create the menu parts
    JMenuBar menuBar = new JMenuBar();
    JMenu menuFile = new JMenu("File");
    JMenu menuHelp = new JMenu("Help");
    JMenuItem menuFileWebsite = new JMenuItem("Website");
    JMenuItem menuFileExit = new JMenuItem("Exit");
    JMenuItem menuHelpRules = new JMenuItem("Rules");
    JMenuItem menuHelpAbout = new JMenuItem("About");
    JMenuItem menuHelpHow = new JMenuItem("How To Play");

    // make the shortcuts for the items
    menuFile.setMnemonic(KeyEvent.VK_F);
    menuHelp.setMnemonic(KeyEvent.VK_H);

    // put the menu parts with eachother
    menuBar.add(menuFile);
    menuBar.add(menuHelp);
    menuFile.add(menuFileWebsite);
    menuFile.add(menuFileExit);
    menuHelp.add(menuHelpRules);
    menuHelp.add(menuHelpAbout);
    menuHelp.add(menuHelpHow);


    return menuBar;
}

public static Component setTitle() {
    JLabel title = new JLabel("Welcome To *the game*");
    title.setVerticalAlignment(JLabel.TOP);
    title.setHorizontalAlignment(JLabel.CENTER);
    return title;
}

}

顺便说一句:我想要网站选项(现在就让我们使用它)来使用launchURL方法;我知道那个有效。

3 个答案:

答案 0 :(得分:14)

JMenuItem是一种按钮形式(AbstractButton)。正常模式是使用Action构建您的按钮(请参阅JMenuItem的构造函数)。 Action定义要执行的名称和操作。大多数人会延长AbstractAction并实施actionPerformed,这是在按下按钮时调用的。

可能的实现可能如下所示:

JMenuItem menuItem = new JMenuItem(new AbstractAction("My Menu Item") {
    public void actionPerformed(ActionEvent e) {
        // Button pressed logic goes here
    }
});

或:

JMenuItem menuItem = new JMenuItem(new MyAction());
...
public class MyAction extends AbstractAction {
    public MyAction() {
        super("My Menu Item");
    }

    public void actionPerformed(ActionEvent e) {
        // Button pressed logic goes here
    }
}

请注意,我上面说的所有内容也适用于JButton。另请参阅Java非常有用的How to Use Actions教程。

答案 1 :(得分:2)

你只需要像这样在你的JMenuItem1中添加一个ActionListener:

jMenuItem1.addActionListener(new java.awt.event.ActionListener() {
    public void actionPerformed(java.awt.event.ActionEvent evt) {
        jMenuItem1ActionPerformed(evt);
    }
});

然后在jMenuItem1ActionPerformed(evt)中实现该操作:

private void jMenuItem1ActionPerformed(java.awt.event.ActionEvent evt) {
    // TODO add your handling code here:
    javax.swing.JOptionPane.showMessageDialog(null, "foo");
    // more code...
}

代码:

    ...
    JMenuItem menuFileWebsite = new JMenuItem("Website");
    JMenuItem menuFileExit = new JMenuItem("Exit");
    menuFileExit.addActionListener(new java.awt.event.ActionListener() {
        @Override
        public void actionPerformed(java.awt.event.ActionEvent evt) {
            menuFileExitActionPerformed(evt);
        }
    });
    JMenuItem menuHelpRules = new JMenuItem("Rules");

private static void menuFileExitActionPerformed(java.awt.event.ActionEvent evt) {
    System.exit(0);
}

答案 2 :(得分:2)

要将任何操作添加到按钮中,只需从实现ActionListener接口的类中创建对象:

menuFileWebsite.addActionListener(new ActionListener() {
    public void actionPerformed(ActionEvent e) {
        launchURL("http://www.google.com");
    }
});

这里我们创建实现Actionlistener接口的匿名内部对象,并覆盖actionperforemed方法来完成其工作

我在代码中进行了一些更改,在命名类上遵循java标准,并在EDT中创建任何GUI组件。

// WindowMakerDemo.java

import java.awt.Component;
import java.awt.EventQueue;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;

import javax.swing.*;


public final class WindowMakerDemo  {
    public static void main(String[] args) {
       EventQueue.invokeLater(new Runnable() {
           @Override
           public void run() {
                JFrame frame = new MyFrame();
                frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                frame.setTitle("*Game Title* Beta 0.0.1");
                frame.setSize(600, 400);
                frame.setLocation(100, 100);
                frame.setResizable(false);
                frame.setVisible(true);
           }
       });
    }
}

 final class MyFrame extends JFrame{

    public MyFrame() {
       createWindow();
    }

    private void createWindow() {
        setJMenuBar(menuBarCreator());
        add(setTitle());
    }

    private JMenuBar menuBarCreator() {
        // create the menu parts
        JMenuBar menuBar = new JMenuBar();
        JMenu menuFile = new JMenu("File");
        JMenu menuHelp = new JMenu("Help");

        JMenuItem menuFileWebsite = new JMenuItem("Website");
        JMenuItem menuFileExit = new JMenuItem("Exit");
        JMenuItem menuHelpRules = new JMenuItem("Rules");
        JMenuItem menuHelpAbout = new JMenuItem("About");
        JMenuItem menuHelpHow = new JMenuItem("How To Play");

        // website button action
        menuFileWebsite.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                launchURL("http://www.google.com");
            }
        });

        // exit action
        menuFileExit.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                System.exit(0); 
            }
        });

        // make the shortcuts for the items
        menuFile.setMnemonic(KeyEvent.VK_F);
        menuHelp.setMnemonic(KeyEvent.VK_H);

        // put the menu parts with eachother
        menuBar.add(menuFile);
        menuBar.add(menuHelp);

        menuFile.add(menuFileWebsite);
        menuFile.add(menuFileExit);

        menuHelp.add(menuHelpRules);
        menuHelp.add(menuHelpAbout);
        menuHelp.add(menuHelpHow);

        return menuBar;
    }

    private Component setTitle() {
        JLabel title = new JLabel("Welcome To *the game*");
        title.setVerticalAlignment(JLabel.TOP);
        title.setHorizontalAlignment(JLabel.CENTER);
        return title;
    }

    private void launchURL(String s) {
        String s1 = System.getProperty("os.name");
        try {

            if (s1.startsWith("Windows")) {
                Runtime.getRuntime().exec((new StringBuilder()).append("rundll32 url.dll,FileProtocolHandler ").append(s).toString());
            } else {
                String as[] = {"firefox", "opera", "konqueror", "epiphany",
                    "mozilla", "netscape"};
                String s2 = null;
                for (int i = 0; i < as.length && s2 == null; i++) {
                    if (Runtime.getRuntime().exec(new String[]{"which", as[i]}).waitFor() == 0) {
                        s2 = as[i];
                    }
                }

                if (s2 == null) {
                    throw new Exception("Could not find web browser");
                }
                Runtime.getRuntime().exec(new String[]{s2, s});
            }
        } catch (Exception exception) {
            System.out.println("An error occured while trying to open the            web browser!\n");
        }
    }
}