Hey guys,

I'm trying to code a testing app which will display questions on a JForm for a period of time. I need a way of keeping track of time so I know when the user's time is up.

What should I use? So far, I've found these:

javax.swing.Timer

java.util.Timer

You should use the swing timer for ordinary tasks that relate to swing GUIs. util.timer is for more general/complex timing tasks.

An example I've found; the event only triggers if I leave the first line. Why?

new JFrame().setVisible(true);
    
    

    ActionListener actionListener = new ActionListener() {
      public void actionPerformed(ActionEvent actionEvent) {
        System.out.println("Hello World Timer");
      }
    };

    Timer timer = new Timer(500, actionListener);
    timer.start();

What to do if I want to display my timer in an up-to-date JLabel ? no code, just the logic, or what I should look into. Threads?

Set the timer to fire (eg) once a second. In the ActionListener update the JLabel and keep a running count of the total seconds. When the total reaches your time limit, stop the timer and do whatever else is needed.
The Timer class uses Swing's event dispatch thread and its related queue (same as is used for popping up tooltips after x millisecs etc), so it's a very efficient and solid implementation. You won't need any other threads unless you get into long-running task steps (eg massive computations, or slow network accesses)

Working:

final javax.swing.Timer countdownTimer =  new javax.swing.Timer(1000, null);


        ActionListener cronometru = new ActionListener() {
            public void actionPerformed(ActionEvent evt) {
                
                if (question.cronometruTimp.getText().equals("0:00")){
                    countdownTimer.stop();
                }
                else{
                    if (fereastra1.timp%60 >=10)
                        question.cronometruTimp.setText(Integer.toString(fereastra1.timp / 60) + ":"+ Integer.toString(fereastra1.timp % 60));
                    else
                        question.cronometruTimp.setText(Integer.toString(fereastra1.timp / 60) + ":0"+ Integer.toString(fereastra1.timp % 60));
                }
                fereastra1.timp--;
            }
        };
        
       countdownTimer.addActionListener(cronometru);


        countdownTimer.start();

Thanks!

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.