首先我要感谢大家谁回答的问题。没有你我就不知道了。你们每个人都给了我一个难题。
我最初的问题是:
TextInputListener
类需要访问buttonX
。
TextInputListener
类需要访问textField
。
在TextInputListener类我计算过,它并不真正需要访问的按钮,它只有知道如果e.getSource()
等于button
。因此,我在Window
类中创建了一个方法,其中ActionEvent
作为参数(如e
),将其与buttonX
进行比较,然后返回答案。
//Window.java
...
boolean isButton0(ActionEvent e) {
return e.getSource() == buttons[0];
}
boolean isButton1(ActionEvent e) {
return e.getSource() == buttons[1];
}
...
问题1解决:
所以我现在更近了一步。我可以确定是否按下了button1
,button2
..,但没有声明按钮是公开的,也没有通过像getButton1()
这样的“getter”方法返回它。
// TextInputListener.java
public class TextInputListener implements ActionListener {
Window window;
@Override
public void actionPerformed(ActionEvent e) {
if (window.isButton0(e)) {
//textField.setText("0")
} else if (window.isButton1(e)) {
//textField.setText("1")
}
...
}
}
(TextInputListener.java和Window.java是在相同的封装所以我能够申报方法包私人。)
问题2解决:
一旦再次TextInputListener
并不真的需要textField
(作为一个变量)它只需要设置其文本。所以我创建了另一个包私钥方法setOutputText(String text)
来设置文本。下面的代码:
// Window.java
public class Window {
TextField textField;
JButton button1;
JButton button2;
...
void setText(String text) {
textField.setText(text);
}
}
// TextInputListener.java
public class TextInputListener implements ActionListener {
Window window;
@Override
public void actionPerformed(ActionEvent e) {
if (window.isButton0(e)) {
window.setText("0");
} else if (window.isButton1(e)) {
window.setText("1");
}
...
}
}
把一切TOGETHER:
现在剩下的工作就是让类的每个实例来了解彼此的唯一的事情。在TextInputListener
类添加以下代码:
public void listenTo(Window window) {
this.window = window;
}
在Window类我不得不把ActionListener
添加到每个按钮,所以我加了如下代码:
public void setActionListener(ActionListener l) {
for (int i = 0; i < buttons.length; i++) {
buttons[i].addActionListener(l);
}
}
这基本上!主要设置一切,它的工作。下面是(几乎)完整的最终代码:
// MyApp.java
public class MyApp {
public static void main(String[] args) {
Window myWindow = new Window();
TextInputListener myTextInputListener = new TextInputListener();
myWindow.setActionListener(myTextInputListener);
myTextInputListener.listenTo(myWindow);
}
}
// Window.java
public class Window {
TextField textField;
JButton button1;
JButton button2;
...
void setText(String text) {
textField.setText(text);
}
public void setActionListener(ActionListener l) {
for (int i = 0; i < buttons.length; i++) {
buttons[i].addActionListener(l);
}
}
}
// TextInputListener.java
public class TextInputListener implements ActionListener {
Window window;
public void listenTo(Window window) {
this.window = window;
}
@Override
public void actionPerformed(ActionEvent e) {
if (window.isButton0(e)) {
window.setText("0");
} else if (window.isButton1(e)) {
window.setText("1");
}
...
}
}
#1)扩展Action而不是实现ActionListener。 #2)你可以在Window类中定义动作,或者传入将要操作的参数。这两种方法都很好。 –