Search code examples
javaswingtimerjlabel

no luck with javax timer with Jlabel


I'm still having issues with updating the JLabel using a timer. I can't seem to figure out what I am missing. the global second variable stays at zero so I am guessing the timers working but not updating the GUI window?

 import javax.swing.*;
import java.awt.*;
import java.awt.event.*;

class Globals 
{
    public static int seconds = 0;
}

class main
{
    public static void main(String Args[])
    {

        //text timeline = new text();
        JFrame testing = new JFrame();
        frame textdes = new frame();
        testing.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        testing.setSize(1000,1000);
        testing.setVisible(true);

        Countdown timer = new Countdown();
        Timer countdown = new Timer(5000, timer);
        countdown.start();

        JLabel countdowntext = new JLabel();
        countdowntext.setText("Now its :" + Globals.seconds);
        testing.add(countdowntext);     
        testing.add(textdes);

    }
}

class frame extends JFrame
{
    class Countdown implements ActionListener 
    {
        public void actionPerformed(ActionEvent e)
        {
            Globals.seconds++;
        }
    }
}

Solution

  • You're setting the text of the label only once in the program. Then the timer changes the value of a variable, but doesn't do anything with the label. It should do:

    Globals.seconds++;
    countdowntext.setText("Now its :" + Globals.seconds);
    

    Here's a complete example:

    import javax.swing.*;
    import java.awt.*;
    import java.awt.event.*;
    
    class Globals {
        public static int seconds = 0;
    }
    
    class Main {
        public static void main(String Args[]) {
    
            //text timeline = new text();
            JFrame testing = new JFrame();
            testing.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            testing.setSize(1000,1000);
            testing.setVisible(true);
    
            JLabel countDownLabel = new JLabel();
            countDownLabel.setText("Now it's : " + Globals.seconds);
            testing.add(countDownLabel);
    
            CountDown countdown = new CountDown(countDownLabel);
            Timer timer = new Timer(5000, countDown);
            timer.start();
        }
    }
    
    class CountDown implements ActionListener {
        private JLabel countDownLabel;
    
        public CountDown(JLabel countDownLabel) {
            this.countDownLabel = countDownLabel;
        }
    
        @Override
        public void actionPerformed(ActionEvent e) {
            Globals.seconds++;
            this.countDownLabel.setText("Now it's : " + Globals.seconds);
        }
    }