14

我正在制作一个有 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 方法;我知道一个有效。

4

3 回答 3

17

AJMenuItem是按钮 ( 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教程。

于 2012-03-19T22:07:08.973 回答
4

虽然使用 Actions 更好,但您也可以像这样将 ActionListener 添加到 JMenuItem1 中:

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);
}
于 2012-03-19T22:12:02.277 回答
2

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

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

这里我们创建实现 Actionlistener 接口的匿名内部对象,并重写 actionperformed 方法来完成它的工作

我对您的代码进行了一些更改,以遵循命名类的 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");
        }
    }
}
于 2012-03-19T22:25:13.440 回答