有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java如何利用辅助类来处理事件?

我创建了两个独立的类,而我实例化了我的菜单栏,还有一个类来处理事件;因为我在菜单栏上有很多选择,我想处理

我已经设置好了菜单栏和它的结构,现在下一步是在用户单击菜单栏上的选项时处理事件

以下是我的主菜单栏类中的两个项目的片段:

    JMenuItem addOrangeItem = new JMenuItem("Orange");
    addOrangeItem.addActionListener(new MenuActionListener().orangeActionPerformed(e));

    JMenuItem addAppleItem = new JMenuItem("Apple");
    addAppleItem.addActionListener(new MenuActionListener().appleActionPerformed(e));

以下是我的事件处理课程:

public class MenuActionListener implements ActionListener {

    public void orangeActionPerformed(ActionEvent e) {
    }
    @Override
    public void actionPerformed(ActionEvent e) {
        System.out.println("I have chosen an orange!");
    }


    public void appleActionPerformed(ActionEvent e) {
    }
    @Override
    public void actionPerformed(ActionEvent e) {
        System.out.println("I have chosen an apple!");
    }
}

问题在于我的主菜单栏类中的这行代码:

addAppleItem.addActionListener(new MenuActionListener().appleActionPerformed(e));而我的ActionEvent的e下划线为红色,我不知道该怎么做才能让它工作

我的代码的目标是选择Apple/orange项目,然后我的事件处理类将返回一些代码

我的问题是如何编辑以上代码行,以便正确处理菜单栏项

如果你需要更多的信息,请告诉我,我会马上处理

非常感谢您的帮助,谢谢


共 (1) 个答案

  1. # 1 楼答案

    这是无效语法:addActionListener(new MenuActionListener().orangeActionPerformed(e))

    addActionListener想要一个ActionListener对象,而不是void(这是new MenuActionListener().orangeActionPerformed(e)的结果),而且e在这里是一个未知变量

    这将起作用:addActionListener(new MenuActionListener()),但由于您需要根据按下的项目执行不同的操作,因此可以使用操作命令系统:

    JMenuItem上设置一个操作命令(还要注意ActionListener的一个实例对两个按钮都足够了):

    ActionListener listener = new MenuActionListener();
    
    JMenuItem addOrangeItem = new JMenuItem("Orange");
    addOrangeItem.setActionCommand("orange");// set action command
    addOrangeItem.addActionListener(listener);
    
    JMenuItem addAppleItem = new JMenuItem("Apple");
    addAppleItem.setActionCommand("apple");// set action command
    addAppleItem.addActionListener(listener);
    

    然后在侦听器中检索action命令(在actionPerformed),并决定要执行的操作:

    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    
        public class MenuActionListener implements ActionListener {
    
            public void orangeActionPerformed() {
                System.out.println("I have chosen an orange!");
            }
    
            public void appleActionPerformed() {
    
                System.out.println("I have chosen an apple!");
    
            }
    
            @Override
            public void actionPerformed(final ActionEvent e) {
    
                String command = e.getActionCommand();
    
                switch (command) {
    
                case "orange":
                    orangeActionPerformed();
                    break;
                case "apple":
                    appleActionPerformed();
                    break;
                default:
    
                }
    
            }
        }
    

    注意setActionCommand是来自AbstractButton的一个方法,例如,它也适用于JButton