因此,我要完成的工作是将ActionListener添加到另一个类中定义的按钮上,而不会破坏该按钮的封装。
我的GUI类:
public class GUI extends JFrame {
private JButton button;
public GUI () {
this.button = new JButton ();
}
public void setText (Text text) {
this.button.setText (text);
}
public JButton getButton () {
return this.button;
}
}
我的游戏课:
public class Game {
private GUI gui;
public Game () {
this.gui = new GUI ();
this.gui.getButton ().addActionListener (new ActionListener () {
public void actionPerformed (ActionEvent evt) {
play ();
}
});
}
public void play () {
this.gui.setText ("Play");
}
}
然后,在Main类中调用一个新的Game实例。
我想摆脱GUI类中的getter,否则使用文本setter或类似的setter没有意义。
当我将ActionListener添加到GUI构造函数中时,将无法访问Game方法。有没有我看不到的解决方案?
最佳答案
让GUI
将动作侦听器添加到按钮,让Game
创建动作侦听器:
public class GUI extends JFrame {
public void addActionListenerToButton(ActionListener listener) {
button.addActionListener(listener);
}
....
}
public class Game {
private GUI gui;
public Game () {
this.gui = new GUI ();
this.gui.addActionListenerToButton (new ActionListener () {
public void actionPerformed (ActionEvent evt) {
play ();
}
});
}
...
}
另外,也可以只传递功能接口,而不要传递完整的
ActionListener
。