Java swing倒计时器无法正常工作

时间:2016-05-26 11:19:32

标签: java dynamic timer dialog countdown

我想制作一个在特定时间后关闭计算机的程序,但我在计时器倒计时时遇到麻烦。它必须减少旋转器所需的时间。我尝试制作动态对话框应用程序,但它不起作用 如果这还不够,我会应用whole code

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);
        }
    });

1 个答案:

答案 0 :(得分:0)

您正在更新值,如果m_secs < 0

移动

hours.setValue((Integer) m_hours);
minutes.setValue((Integer) m_mins);
seconds.setValue((Integer) m_secs);

在if-block之外,它将更新标签。 它现在应该是这样的:

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");
                }
        }
    });