-1

I have been working on a cafe management system which has a GUI. I'd like to add a dynamic date to one of my textfiled. I found something like this;

            DateTimeFormatter dtf = DateTimeFormatter.ofPattern("HH:mm:ss MM/dd/yyyy "); 
            while(true){
                LocalDateTime now = LocalDateTime.now();  
                jTextArea6.setText(dtf.format(now));
            }

When I try to add that code to my program it doesn't work. It probably happens because of while loop. What do you recommend? I saw some kinda thread issues but many of those posts shared 8-9 years ago.

hburak_06
  • 25
  • 9
  • @Tom nah nah it didn't work – hburak_06 Dec 30 '20 at 10:52
  • 1
    You are blocking the UI thread because of your while loop. Remove it and you will see it works. You should be using a [SwingWorker](https://docs.oracle.com/javase/8/docs/api/javax/swing/SwingWorker.html) to perform any long running tasks so that you don't block the UI thread and using `publish` on the `SwingWorker` to publish results to the UI. Or alternatively a Swing timer as suggested by @Tom. A reply like *nah nah it didn't work* is not helpful either. – David Kroukamp Dec 30 '20 at 11:16

1 Answers1

1

Copy and paste below method into your code and Call it on start of your application.

    public void updateFieldDate()
{
        Thread Clock = new Thread()
        {
            public void run()
                {
                    for(;;)
                    {
                        try 
                        {
                            sleep(1000);
                            DateTimeFormatter dtf = DateTimeFormatter.ofPattern("HH:mm:ss MM/dd/yyyy "); 
                            LocalDateTime now = LocalDateTime.now();  
                            jTextArea6.setText(dtf.format(now));
                        }
                        catch (Exception e)
                        {
                            System.out.println("Error");
                        }
                    }
                }
        };
        Clock.start();
}
  • 1
    All swing components should be created on the event dispatch thread and thus any updates made to a Swing component should be done on the Event Dispatch Thread via `SwingUtilities.invokeLater` or a `SwingWorker` should be used in place of a `Thread` – David Kroukamp Dec 30 '20 at 11:15