简体   繁体   中英

Implementing a timer into a java program

I'm creating a java paint program and can't figure out how to implement a timer that starts when the GUI is opened so the user can see their time spent drawing so far. My code is pasted below. I'm a complete beginner and have searched all the oracle documents and can't understand them so any help is appreciated! Hopefully there's a simple way of implementing this.

I added a JLabel onto my toolbar so I can try and post the "Drawing Time: "+totalTime but it stays at 0 for some reason I don't know how to make it refresh every second...

I would try something like this:

Set up the Global Variables (Make sure you fix your imports)

public class MainWindow extends javax.swing.JFrame implements ActionListener{

//global variable for tracking time
Timer timer;
final int DELAY = 1000;   //the delay for the timer (1000 milliseconds)
int myCounter;

then initialize the timer and counter and make sure to send the info from the counter to your label

public MainWindow() {
    initComponents();

    //initialize the timer and the counter
    timer = new Timer(DELAY, this);
    timer.start();
    myCounter = 0;
}

//method needed for the timer, since this class implements ActionListener
//this method will get called however often the DELAY is set for
@Override
public void actionPerformed(ActionEvent e){
    myCounter++;
    labelOutput.setText(Integer.toString(myCounter));
}//end of method

This is a pretty basic example of setting up a timer, so if you just apply the steps taken in the code I've given you to your own application, you'll probably be able to get it working. Good luck!

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