嗨伙计们我是java的新手...... :( 我只想让我的按钮(开始)启动一个计时器,但我想用'if'自动停止计时器,例如...当用户输入一个时间并且计时器到达计时器时它停止...到目前为止我的编码是这样的......
private void startTimerActionPerformed(java.awt.event.ActionEvent evt) {
javax.swing.Timer tm = new javax.swing.Timer(100, new ActionListener()
{
public void actionPerformed (ActionEvent evt) {
AddOneActionPerformed(evt);
}
});
tm.start();
int getTM,getM,getTS,getS,Secs,tenSec,Mins,tenMin;
getTM = Integer.parseInt(enterTenMins.getText());
getM = Integer.parseInt(enterOneMins.getText());
getTS = Integer.parseInt(enterTenSecs.getText());
getS = Integer.parseInt(enterOneSecs.getText());
tenMin = Integer.parseInt(tenMins.getText());
Mins = Integer.parseInt(oneMins.getText());
tenSec = Integer.parseInt(tenSecs.getText());
Secs = Integer.parseInt(oneSecs.getText());
}
和AddOneActionPerformed(evt)
是
private void AddOneActionPerformed(java.awt.event.ActionEvent evt) {
int dd,Secs,tenSec,Mins,tenMin;
tenMin = Integer.parseInt(tenMins.getText());
Mins = Integer.parseInt(oneMins.getText());
tenSec = Integer.parseInt(tenSecs.getText());
Secs = Integer.parseInt(oneSecs.getText());
dd= Integer.parseInt(digitValue.getText());
dd= dd+1;
if (dd==10)
dd = 0;
if (Secs == 10)
Secs = 0;
if (dd==0)
Secs=Secs +1;
if (tenSec>=6)
tenSec = 0;
if (Secs==10)
tenSec=tenSec +1;
if (Mins==10)
Mins = 0;
if (tenSec==6)
Mins=Mins+1;
if (tenMin>=6)
tenMin=0;
if (Mins==10)
tenMin=tenMin+1;
String ss = Integer.toString(dd);
digitValue.setText(ss);
String ff = Integer.toString(Secs);
oneSecs.setText(ff);
String gg = Integer.toString(tenSec);
tenSecs.setText(gg);
String hh = Integer.toString(Mins);
oneMins.setText(hh);
String jj = Integer.toString(tenMin);
tenMins.setText(jj);
showDigitActionPerformed(evt);
showOneSecsActionPerformed(evt);
showTenSecsActionPerformed(evt);
showOneMinsActionPerformed(evt);
showTenMinsActionPerformed(evt);
}
答案 0 :(得分:2)
您可以从ActionEvent的getSource()
方法获取Timer实例,然后在其上调用stop。所以,...
// for your Timer's ActionListener
@Override
public void actionPerformed(ActionEvent evt) {
if (someStoppingConditionIsTrue) {
Timer timer = (Timer) evt.getSource();
timer.stop();
} else {
// code to call repeatedly
}
}
请注意,您还有两个单独的问题,应该单独解决。上面的代码是一种使用某种条件在自己的ActionListener中停止Timer的方法。您的另一个问题是如何获取用户输入以允许您更改该条件,这将涉及独立于上述Timer代码的单独代码。
另外考虑一下:
String.format("%02d:%02d", minutes, seconds)
。