我构建了一个 GameFrame 类,其中包含一个带有 jmenubar
的 JFrame,并向菜单添加了一些项目。出于 OOP 的原因,我将 actionlistener 类(实现我自己的类并将其作为参数传递给框架 jmenubar)与 GameFrame 分开。
问题是,当选择其中一个 JmenuItems
时,它应该弹出一个对话框,要求用户输入 URL。但是这个对话框只有在选择菜单项时才会创建,所以我如何避免执行以下操作? (这不是很 OOP)
@Override
public void actionPerformed(ActionEvent e) {
JMenuItem item = (JMenuItem) e.getSource();
if (item.getText().equals("URL")) {
//create a dialogue
//get the input
//pass it to something else
}
}
我想避免在我的事件处理程序类中创建 swing 组件,并避免在我的组件类中创建事件处理程序,但我看不出有什么办法可以解决。
最佳答案
创建一个自定义的 ActionLIstener
,并为构造函数传递它需要引用的项目的引用(即使您放置监听器的对象与 actionPerformed( )
方法。
class MyActionListener implements ActionListener {
JMenuItem item;
MyActionListener(JMenuItem item) {
this.item = item;
}
public void actionPerformed(ActionEvent e) {
// here you have the reference for the item. Printing the text:
System.out.println(item.getText());
}
}
这种方法的缺点是每个 JMenuItem 都需要一个监听器。
关于java - jmenuitem选择对话,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15796220/