[英]Java swing countdown timer not working properly
I would like to make a program that shuts down the computer after specific time, but I have troubles making the timer countdown. 我想制作一个在特定时间后关闭计算机的程序,但是我无法使计时器倒数。 It must decrement the time in the spinners from which it takes it.
它必须减少花费在微调器中的时间。 I tried to make a dynamic dialog application but it doesn't work.
我试图制作一个动态对话框应用程序,但是它不起作用。
I apply the whole code if that is not enough. 如果那还不够的话,我会应用整个代码 。
timer.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
//decrements the amount of seconds and the time in the spinners
m_secs--;
ShutDownDialog.this.AmountOfTime--;
if (m_secs<0) {
m_secs=59;
m_mins--;
if (m_mins<0) {
m_mins=59;
m_hours--;
if(m_hours<0)
m_hours=0;
}
hours.setValue((Integer)m_hours);
minutes.setValue((Integer)m_mins);
seconds.setValue((Integer)m_secs);
label_2.setText(ShutDownDialog.
this.AmountOfTime.toString());
}
if (ShutDownDialog.this.AmountOfTime< 0)
{
timer.stop();
label_2.setText("stop"); //just to check what happens
}
}
});
StartCountdown.addMouseListener(new MouseAdapter() {
@Override
public void mouseClicked(MouseEvent arg0) {
hours.setEnabled(false);
minutes.setEnabled(false);
seconds.setEnabled(false);
StartCountdown.setEnabled(false);
StopCount.setEnabled(true);
//calculates the amount of seconds and starts the timer
m_hours = ((Integer)hours.getValue()*3600); //get the hours
m_mins = ((Integer)minutes.getValue()*60); //get the minutes
m_secs = (Integer)seconds.getValue(); //get seconds
AmountOfTime = m_hours + m_mins + m_secs;
timer.start();
//JOptionPane.showMessageDialog(null, AmountOfTime);
}
});
You are updating the values only, if m_secs < 0
. 如果
m_secs < 0
,则仅更新值。
Move 移动
hours.setValue((Integer) m_hours);
minutes.setValue((Integer) m_mins);
seconds.setValue((Integer) m_secs);
outside of the if-block and it will update the labels. 在if块之外,它将更新标签。 It should now look like this:
现在看起来应该像这样:
private void initialize() {
timer.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
m_secs--;
ShutDownDialog.this.AmountOfTime--;
if (m_secs<0) {
m_secs=59;
m_mins--;
if (m_mins<0) {
m_mins=59;
m_hours--;
if(m_hours<0)
m_hours=0;
}
}
hours.setValue((Integer) m_hours);
minutes.setValue((Integer) m_mins);
seconds.setValue((Integer) m_secs);
label_2.setText(ShutDownDialog.this.AmountOfTime.toString());
if (ShutDownDialog.this.AmountOfTime< 0)
{
timer.stop();
label_2.setText("stop");
}
}
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.