Java clock isn't counting in Swing

前端 未结 1 1874
孤城傲影
孤城傲影 2020-12-20 10:26

I am trying to make a stopwatch using swing, but it is not working. Here is my code. The Jlabel clock is always displaying -1, which should only happen if it is stopped. Am

相关标签:
1条回答
  • 2020-12-20 11:00

    Your StopWatch class run once and then terminates...

    public void run() {
        // Start here
        SwingUtilities.invokeLater(new Runnable()
        {
            @Override
            public void run() {
                long time = getElapsedTime();
                sidePanel.this.clock.setText(String.valueOf(time));
            }
        });
        // End here...
    }
    

    A thread will terminate when it exists it's run method, in this case, your StopWatch's run method.

    What you need to do to is maintain a loop until the isRunning becomes false

    public void run() {
        while (isRunning) {
            SwingUtilities.invokeLater(new Runnable()
            {
                @Override
                public void run() {
                    long time = getElapsedTime();
                    sidePanel.this.clock.setText(String.valueOf(time));
                }
            });
            // Because we really don't want to bombboard the Event dispatching thread
            // With lots of updates, which probably won't get rendered any way,
            // We put in a small delay...
    
            // This day represents "about" a second accuracy...
            try {
                Thread.sleep(500);
            } catch (Exception exp) {
            }
        }
    }
    

    It would much simpler to use a javax.swing.Timer though...

    private Timer timer;
    public void init()
    {
        pane = new JPanel();
        pane.setLayout(new BoxLayout(pane, BoxLayout.Y_AXIS));
    
        clock = new JLabel("00:00");
    
        toggle = new JButton("Start/Stop");
        toggle.addActionListener(this);
    
        pane.add(clock);
        pane.add(toggle);
    
        timer = new Timer(500, new ActionListener() { 
            public void actionPerformed(ActionEvent evt) {
                long time = getElapsedTime();
                sidePanel.this.clock.setText(String.valueOf(time));        
            }
        });
        timer.setRepeats(true);
        add(pane);
    
    }
    
    @Override
    public void actionPerformed(ActionEvent e) {
        if(e.getSource() == toggle)
        {
            if(timer.isRunning())
            {
                endTime = System.currentTimeMillis();
                timer.stop();
            }
            else
            {
                startTime = System.currentTimeMillis();
                timer.start();
            }
        }
    }
    

    You can then strip out the functionality from you StopWatch (ie the getElapsedTime())

    0 讨论(0)
提交回复
热议问题