简体   繁体   中英

Displaying a timer in a panel using JLabel

So I am making a program with a fellow classmate and we haven't had much experience with GUI but what I am trying to do is display a timer of how long a user takes to complete a puzzle in a side panel (there's a main game area and a side panel beside it with buttons and such) but I'm not sure how I can get the JLabel to constantly update with the time that the user takes to solve the puzzle. I don't know how I can use a timer object to do this so I've tried to use just System.nanoTime() for now.

1) if I am using a timer object, what do I use in the Action listener parameters? Will this call the timerLabel.updateUI(); each time (assuming I have the actionPerformed method with that line of code in it already)? Using a timer object what will I need to put into the Jlabel param when creating it?

2) if not using the timer object what would be the best way to update the time constantly?

//Timer timer = new Timer(1000, new ActionListener(??));
//timer.start();
long start = System.nanoTime();
String time = new java.text.SimpleDateFormat("ms").format(new java.util.Date(start/1000000));
timerlabel = new JLabel(time);
sideMenu.add(timerlabel);
timerlabel.updateUI();

You don't seem to understand how to use the ActionListener . ActionListener doesn't take any parameters as it is an interface; instead, you override its actionPerformed method. What you might be looking for is this:

Timer timer = new Timer(1000, new ActionListener() {
    @Override
    public void actionPerformed(ActionEvent ev) {
        // Whatever action you want to happen every 1000 milliseconds
        timerLabel.setText(new java.text.SimpleDateFormat("ms")
            .format(new java.util.Date(System.nanoTime()/1000000)));
    }
});
timer.start();

See here for more details or here for a pretty good example.

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