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 楼答案
这是无效语法:
addActionListener(new MenuActionListener().orangeActionPerformed(e))
addActionListener
想要一个ActionListener
对象,而不是void
(这是new MenuActionListener().orangeActionPerformed(e)
的结果),而且e
在这里是一个未知变量这将起作用:
addActionListener(new MenuActionListener())
,但由于您需要根据按下的项目执行不同的操作,因此可以使用操作命令系统:在
JMenuItem
上设置一个操作命令(还要注意ActionListener
的一个实例对两个按钮都足够了):然后在侦听器中检索action命令(在
actionPerformed
),并决定要执行的操作:注意
setActionCommand
是来自AbstractButton的一个方法,例如,它也适用于JButton