button2.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { i++; next.setEnabled(true); if (button2.getText().equals(rightanswer)) { right++; score.setText(right + "/" + i); show.setText("correct!"); button2.setBackground(Color.green); } else { show.setText("wrong"); score.setText(right + "/" + i); button2.setBackground(Color.pink); } rightanswer = this.getAnswer(i);; unenabled(); next.setEnabled(true); } private String getAnswer(int i) { // TODO Auto-generated method stub return null; } });怎么把getanswer移到actionlisterner外面,在方法内部调用?
时间: 2024-01-18 22:02:35 浏览: 64
你可以将 `getAnswer()` 方法移到 `ActionListener` 外面,然后在 `ActionListener` 内部调用该方法。代码如下:
```java
private String getAnswer(int i) {
// TODO Auto-generated method stub
return null;
}
button2.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
i++;
next.setEnabled(true);
if (button2.getText().equals(rightanswer)) {
right++;
score.setText(right + "/" + i);
show.setText("correct!");
button2.setBackground(Color.green);
} else {
show.setText("wrong");
score.setText(right + "/" + i);
button2.setBackground(Color.pink);
}
rightanswer = getAnswer(i);
unenabled();
next.setEnabled(true);
}
});
```
注意,在 `ActionListener` 内部调用 `getAnswer()` 方法时,不需要使用 `this.getAnswer()`,直接使用 `getAnswer()` 即可。
阅读全文