【发布时间】:2014-10-13 22:08:29
【问题描述】:
我有两个计时器。按下按钮 1 时它们都应该被激活,按下按钮 3 时它们都应该停止。如果激活,则每隔一秒,定时器将值 1 添加到它们各自的计数器,即 counter 和 counter1。
如果按下停止按钮,则只有第一个计时器的计数器应重置为零,而第二个计时器的计数器应保持不变。
所以如果我按开始,10 秒后按停止,那么第一个计数器的值应该再次为 0,而第二个计数器的值应该为 10。
如果我在此之后再次按开始,10 秒后再次按停止,第一个计数器的值应该再次为 0,而第二个计数器的值现在应该为 20。
我遇到的问题是,无论我做什么,如果我按下停止,第二个计数器的值就会一直重置,所以每次按下停止它都会再次变为 0,而不是保存与停止按钮之前相同的值被按下(所以在示例中应该是 20)。
这是代码(我留下了一些不重要的东西,如果需要可以上传完整的代码):
public class ColoredWordsExperiment {
Timer timer;
Timer timer1;
TimerAction timeraction;
TimerAction1 timeraction1;
int counter;
int counter1;
ColoredWordsExperiment() {
button1 = new JButton("Matching");
button3 = new JButton("Finished");
buttonHandler = new ButtonHandler(this);
button1.addActionListener(buttonHandler);
button3.addActionListener(buttonHandler);
counter = 0;
timeraction = new TimerAction(this);
timer = new Timer(1000, timeraction);
timer.setInitialDelay(1000);
counter1 = 0;
timeraction1 = new TimerAction1(this);
timer1 = new Timer(1000, timeraction1);
timer1.setInitialDelay(1000);
}
public static void main(String[] arg) {
new ColoredWordsExperiment();
}
}
-
class ButtonHandler implements ActionListener {
ColoredWordsExperiment coloredWords;
public ButtonHandler(ColoredWordsExperiment coloredWords) {
this.coloredWords = coloredWords;
}
@Override
public void actionPerformed(ActionEvent e){
//if button1 pressed
if (e.getActionCommand().equals("Matching")) {
coloredWords.timer.start();
coloredWords.timer1.start();
//if button3 pressed
} else if (e.getActionCommand().equals("Finished")) {
coloredWords.timer.stop();
coloredWords.counter = 0;
coloredWords.timer1.stop();
}
-
class TimerAction implements ActionListener {
ColoredWordsExperiment coloredWords;
public TimerAction(ColoredWordsExperiment coloredWords) {
this.coloredWords = coloredWords;
}
@Override
public void actionPerformed(ActionEvent event) {
coloredWords.counter++;
}
}
-
class TimerAction1 implements ActionListener {
ColoredWordsExperiment coloredWords;
public TimerAction1(ColoredWordsExperiment coloredWords) {
this.coloredWords = coloredWords;
}
@Override
public void actionPerformed(ActionEvent event) {
coloredWords.counter1++;
}
}
【问题讨论】:
-
也许我遗漏了一些东西,但我在发布的代码中看不到您的问题的原因。这向我表明问题可能存在于未发布的代码中。作为一个侧面问题,我确实担心您的代码对字段的非 OOP 直接操作。这增加了复杂性增加的风险和可能的看不见的副作用,而良好的 OOP 实践旨在减少这种情况。