Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 674129
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 14, 20262026-05-14T00:40:19+00:00 2026-05-14T00:40:19+00:00

With the help of people on stackoverflow I was able to get the following

  • 0

With the help of people on stackoverflow I was able to get the following working code of a simple GUI countdown (which just displays a window counting down seconds). My main problem with this code is the invokeLater stuff.

As far as I understand invokeLater, it sends a task to the event dispatching thread (EDT) and then the EDT executes this task whenever it “can” (whatever that means). Is that right?

To my understanding, the code works like this:

  1. In the main method we use invokeLater to show the window (showGUI method). In other words, the code displaying the window will be executed in the EDT.

  2. In the main method we also start the counter and the counter (by construction) is executed in another thread (so it is not in the event dispatching thread). Right?

  3. The counter is executed in a separate thread and periodically it calls updateGUI. updateGUI is supposed to update the GUI. And the GUI is working in the EDT. So, updateGUI should also be executed in the EDT. It is the reason why the code for the updateGUI is enclosed in invokeLater. Is that right?

What is not clear to me is why we call the counter from the EDT. Anyway, it is not executed in the EDT. It starts immediately, a new thread and the counter is executed there. So, why can we not call the counter in the main method after the invokeLater block?

import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.SwingUtilities;

public class CountdownNew {

    static JLabel label;

    // Method which defines the appearance of the window.   
    public static void showGUI() {
        JFrame frame = new JFrame("Simple Countdown");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        label = new JLabel("Some Text");
        frame.add(label);
        frame.pack();
        frame.setVisible(true);
    }

    // Define a new thread in which the countdown is counting down.
    public static Thread counter = new Thread() {
        public void run() {
            for (int i=10; i>0; i=i-1) {
                updateGUI(i,label);
                try {Thread.sleep(1000);} catch(InterruptedException e) {};
            }
        }
    };

    // A method which updates GUI (sets a new value of JLabel).
    private static void updateGUI(final int i, final JLabel label) {
        SwingUtilities.invokeLater( 
            new Runnable() {
                public void run() {
                    label.setText("You have " + i + " seconds.");
                }
            }
        );
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                showGUI();
                counter.start();
            }
        });
    }

}
  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-05-14T00:40:19+00:00Added an answer on May 14, 2026 at 12:40 am

    If I understand your question correctly you’re wonder why you can’t do this:

    public static void main(String[] args) {
        SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                showGUI();
            }
        });
        counter.start();
    }
    

    The reason why you can’t do it is because the scheduler makes no guarantees… just because you invoked showGUI() and then you invoked counter.start() doesn’t mean that the code in showGUI() will be executed before the code in the run method of the counter.

    Think of it this way:

    • invokeLater starts a thread and that thread is schedules an asynchronous event on the EDT which is tasked with creating the JLabel.
    • the counter is a separate thread that depends on the JLabel to exists so it can call label.setText("You have " + i + " seconds.");

    Now you have a race condition: JLabel must be created BEFORE the counter thread starts, if it’s not created before the counter thread starts, then your counter thread will be calling setText on an uninitialized object.

    In order to ensure that the race condition is eliminated we must guarantee the order of execution and one way to guarantee it is to execute showGUI() and counter.start() sequentially on the same thread:

    public static void main(String[] args) {
        SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                showGUI();
                counter.start();
            }
        });
    }
    

    Now showGUI(); and counter.start(); are executed from the same thread, thus the JLabel will be created before the counter is started.

    Update:

    Q: And I do not understand what is special about this thread.
    A: Swing event handling code runs on a special thread known as the event dispatch thread. Most code that invokes Swing methods also runs on this thread. This is necessary because most Swing object methods are not “thread safe”: invoking them from multiple threads risks thread interference or memory consistency errors. 1

    Q: So, if we have a GUI why should we start it in a separate thread?
    A: There is probably a better answer than mine, but if you want to update the GUI from the EDT (which you do), then you have to start it from the EDT.

    Q: And why we cannot just start the thread like any other other thread?
    A: See previous answer.

    Q: Why we use some invokeLater and why this thread (EDT) start to execute request when it’s ready. Why it is not always ready?
    A: The EDT might have some other AWT events it has to process.
    invokeLater Causes doRun.run() to be executed asynchronously on the AWT event dispatching thread. This will happen after all pending AWT events have been processed. This method should be used when an application thread needs to update the GUI. 2

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I just started working on a website that will help people understand what rappers
Hi Stackoverflow people, I am working on an organisation registration, in which orgs can
Ok, people, I need your help. I've found some code here on Stackoverflow (can't
Hopefully the good people at Stackoverflow can help me today - I basically drank
Can u people Help me How to get the sqlserver name used by sharepoint
Hi people thanks for the help. Im trying to implement a simple pagination that
I just got referred to stackoverflow by a friend here to help with a
Good people of StackOverflow, please help. I've set up an ejabberd server on my
Great people of StackOverflow, save my ass please :) I've been trying to get
With the help of the good people of StackOverflow, I have these two methods:

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.