0

I found an example of how to do a repeating task in java. Now I want that the label's text changes every second. How do I do that? I get the error: non-static method repeatingTask() cannot be referenced from a static context

Somehow the JLabel is not static but public static void main is of course static...

public class whathappens {
    StartGUI startGUI = new StartGUI();
    
    
    public void repeatingTask(){
        getJLabel1().setText("Running: "+ new java.util.Date());
    }
    
    public static void main(String[] args) {
        StartGUI.main(args);
        
        Timer timer = new Timer();
        timer.schedule(new TimerTask() {
            @Override
            public void run() {
                repeatingTask();
                System.out.println("Running: " + new java.util.Date());
            }
        }, 0, 1000);
    }
}

My idea was to call the method getJLabel1() from startGUI class to change the label within "whathappens" class

Andrew Thompson
  • 168,117
  • 40
  • 217
  • 433
Unkannt
  • 9
  • 1

1 Answers1

2

Your not clear about how you get your JLabel. One way or another, your timer task must hold a reference to the JLabel. You can try something like that :

JLabel label = new JLabel();
Timer timer = new Timer(1000, e -> label.setText("Running: " + new Date());
timer.start();

This code uses javax.swing.Timer which is better than java.util.Timer in your context as if fires event within the https://en.wikipedia.org/wiki/Event_dispatching_thread. And it is in this thread that GUI code must be updated.

Seb34
  • 86
  • 2
  • I get my JLabel through a getter which just returns the label. But in your code I have still the problem with static and non-static context. non-static variable JLabel1 cannot be referenced from a static context – Unkannt Mar 26 '21 at 14:45
  • @Unkannt, Your code should NOT have static variables and methods. See: https://stackoverflow.com/questions/25084248/no-delay-in-gui-execution-even-after-implementing-sleep-in-a-separate-thread/25084314#25084314 for a complete example showing how to better structure your code. Use that example as a starting point and then customize. – camickr Mar 26 '21 at 15:02
  • @seb34 good answer (1+). Maybe in the future you can reference the [Swing tutorial](https://docs.oracle.com/javase/tutorial/uiswing/TOC.html) as it contains section on most Swing basics the OP can use as a reference in the future. For example there are sections on the "Concurrency in Swing" which explains the EDT and on "How to Use Swing Timers". Both section directly related to this question/answer. – camickr Mar 26 '21 at 15:06
  • @camickr I will have a look ak the link. But I am not useing a static method on purpose. It is the public static main method which I cant change to non-static. – Unkannt Mar 26 '21 at 15:16
  • @Unkannt What part of the working code in the link I provided to you not understand? – camickr Mar 26 '21 at 16:41