简体   繁体   中英

Counting and printing time in java using swing

I'm trying to implement a timer using one thread and print it on a JButton using another thread. my class for time is like this:

public class Time extends Thread 
{
int counter = 0;
public String currentTime = new String();


public String printFormat(int second)
{
    return String.format("%d:%d", second/60, second%60);
}

synchronized public void count(int minute) throws InterruptedException
{
    minute *= 60;
    while(minute >= 0)
    {
        wait(1000);
        minute--;
        currentTime = printFormat(minute);
        System.out.println(currentTime);
    }

}

and my main thread is like this:

     button.setText(time.currentTime);

what is wrong with this piece of code?

"if you can explain it using java swing timer , I would appreciate that"

If you want to use a javax.swing.Timer do the following, it really simple.

  • The same way you set a ActionListener to a button, you do the same for the timer. Except instead of the button firing the event, it's fired by the timer, every duration period you set for it.
  • In the case of a clock like timer, you would set it to 1000, indication do something every 1000 milliseconds.

In this particular example, I just set the text of the button with a count value that I increment by one every time the timer event is fired. Heres the Timer code

Timer timer = new Timer(1000, new ActionListener(){
    public void actionPerformed(ActionEvent e) {
        button.setText(String.valueOf(count));
        count++;
    }
});
timer.start();

As you can see it' pretty simple

You can run this example

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.SwingUtilities;
import javax.swing.Timer;


public class ButtonTimer {

    private JButton button = new JButton(" ");
    private int count = 1;
    public ButtonTimer() {

        Timer timer = new Timer(1000, new ActionListener(){
            public void actionPerformed(ActionEvent e) {
                button.setText(String.valueOf(count));
                count++;
            }
        });
        timer.start();

        JFrame frame = new JFrame();
        frame.add(button);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.pack();
        frame.setLocationRelativeTo(null);
        frame.setVisible(true);
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                new ButtonTimer();
            }
        });
    }
}

If you want help trying to figure out your current code, consider posting a runnable program we can test out. So we can see where you're going wrong.


Here's a tutorial on Concurrency With Swing

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM