java swing, necessary calls in main method [duplicate] - java

This question already has answers here:
What does SwingUtilities.invokeLater do? [duplicate]
(5 answers)
Closed 9 years ago.
When studying for an exam I stumbled upon some lines in java graphics that aren't really clear to me. So i started to glance and check some other programs and they were without those lines.
example:
public static void main(String[] args){
SwingUtilities.invokeLater(new Runnable(){//unknown
public void run(){ //lines
JPanel panel = new DrawingPanel();
...
}
now i know that Runnable and run have to deal with threads, but i don't know why and how do these two lines work

Swing objects can only be accessed from the Swing thread that runs in closed loop handling repaints, GUI events and so on. When you application starts, it starts in an ordinary thread (not a Swing thread). The lines that look strange to you use SwingUtilities to execute DrawingPanel constructor and probably more code in the Swing thread.
The code that instantiates the first GUI frame directly from the main thread may also work in practice if it is really the first method ever called (as expected). However it is "fundamentally wrong" approach that may not work later under different machine, if differently called and the like.

Swing is a single threaded framework. All interactions and updates with the UI are expected to be executed from within the context of the Event Dispatching Thread.
Java makes no guarenttees that main is executed within the EDT (I believe they normally call this the main thread). Therefore, you are required to ensure that any of your UI code is synced to the Event Dispatching Thread first.
SwingUtilities.invokeLater, delegates to EventQueue.invokeLater. This basically posts the Runnable instance into the event queue, which is processed by the Event Dispatching Thread.
At some time in the future, the Runnable is popped off the queue and the run method is executed within the EDT
See Initial Threads for more details
You could also look at The Single Thread Rule in Swing, Event-Dispatching Thread Rules for Swing UIs for additional info

Related

Synchronized methods vs SwingUtilities.invokeLater [duplicate]

My question is related to SwingUtilities.invokeLater. When should I use it? Do I have to use each time I need to update the GUI components? What does it exactly do? Is there an alternative to it since it doesn't sound intuitive and adds seemingly unnecessary code?
Do I have to use each time I need to update the GUI components?
No, not if you're already on the event dispatch thread (EDT) which is always the case when responding to user initiated events such as clicks and selections. (The actionPerformed methods etc, are always called by the EDT.)
If you're not on the EDT however and want to do GUI updates (if you want to update the GUI from some timer thread, or from some network thread etc), you'll have to schedule the update to be performed by the EDT. That's what this method is for.
Swing is basically thread unsafe. I.e., all interaction with that API needs to be performed on a single thread (the EDT). If you need to do GUI updates from another thread (timer thread, networking thread, ...) you need to use methods such as the one you mentioned (SwingUtilities.invokeLater, SwingUtilities.invokeAndWait, ...).
Swing is single threaded and all changes to the GUI must be done on EDT
Basic usage for invokeLater()
Main methods should be always wrapped in invokeLater()
Delayed (but asynchronously) action/event to the end of EventQueue,
If EDT doesn't exists then you have to create a new EDT by using invokeLater(). You can test it with if (SwingUtilities.isEventDispatchThread()) {...
There exists invokeAndWait(), but till today I (just my view) can't find a reason for using invokeAndWait() instead of invokeLater(), except hard changes into GUI (JTree & JTable), but just with Substance L&F (excellent for testing consistency of events on the EDT)
Basic stuff: Concurrency in Swing
All output from background tasks must be wrapped in invokeLater()
Every Swing application has at least 2 threads:
The main thread that executes the application
The EDT (Event Dispatching Thread) is a thread that updates the UI (so the UI will not freeze).
If you want to update the UI you should execute code within the EDT.
Methods like SwingUtilities.invokeLater, SwingUtilities.invokeAndWait, EventQueue.invokeLater, EventQueue.invokeAndWait allow you to execute code by the EDT.
My question this time is related to SwingUtilities.invokeLater: When should I use it?
What is key to understand is that Java has a separate thread (EDT) handling Swing related events.
You should use invokeLater() to display the main JFrame of a desktop application (for example), instead of trying to do it in the current thread. It will also create the context for graceful closing of the application later.
That's about it for most applications.
Do I have to use each time I need to update the GUI components? What does it exactly do?
No. If you modify a GUI component, it will trigger an event which is registered for later dispatching by Swing. If there is a listener for this event, the EDT thread will call it somewhere down the road. You don't need to use invokeLater(), just set your listeners on components properly.
Keep in mind that this thread is the same thread drawing frames etc... on your screen. Hence, listeners should not perform complex/long/CPU intensive tasks, otherwise your screen will freeze.
Is there an alternative to it since it doesn't sound intuitive and adds seemingly unnecessary code?
You don't need to write more code than displaying your application with invokeLater() + listeners you are interested in on component. The rest is handled by Swing.
Most user-initiated events (clicks, keyboard) will already be on the EDT so you won't have to use SwingUtilities for that. That covers a lot of cases, except for your main() thread and worker threads that update the EDT.

Do all Swing components run on the EDT by default?

I'm new to Java and after reading many articles about threads and swing I understood that all the invocations of Swing methods should be done on the EDT because Swing is not thread safe. however, I already wrote a couple of quite long Swing applications before reading about the EDT. and all of my applications ran quite fine. So my question is were my Swing applications running on the EDT by default or were they running on a different thread and i was just lucky not to have any issues with them?
Like for example if I add a JButton to a JPanel or JFrame, or if I simply call a JTextField's Field.setText(), will these operations be running on the EDT by default or no?
and if the answer is no, then do I have to explicitly send all my Swing component's methods implementations to run on the EDT by invoking SwingUtilities.invokeLater()
Thanks
Remember objects don't live on threads, only execution of methods happens on a thread.
All action emerging (through listeners) from swing components automatically run on the EDT.
For instance a button you click, the onClicked() function will already run on the EDT so you don't need to do anything.
If you don't create any threads explicitly, your basic application will have a main thread and an EDT (and many other threads that you don't accidentally get your code executed on, until you start using extra frameworks).
The thing you have to do manually is construct the GUI on the EDT. As you can see here this can be done in your main thread as follows:
SwingUtilities.invokeLater(new Runnable() {
public void run() {
MyWindow window = new MyWindow ();
window.setVisible(true);
}
});
If you fail to use the EDT correctly. Everything will seem to work fine, but every now and then you can get very strange behavior (because two threads will be doing things instead of one).
So in summary you have to use invokeLater(), or in some exceptions invokeNow() in the following cases:
Constructing Swing components from the main thread.
Calling swing components from your personally created threads.
Calling swing components from events on threads created by frameworks.
This question contains some tools that can help you automatically detect errors (not all though).
where my Swing applications running on the EDT by default or were they running on a diffrent thread and i was just lucky not to have any issues with them?
They were mostly being ran on the EDT. All the painting and updating that Swing does by itself is on the EDT. Anything you do specifically in your code base that you know wasn't on the EDT, is the code that was not on the EDT. So these would be actions like querying the text of a JLabel, or setting the text of a JLabel, or initializing the JLabel itself.
The various listener methods that are executed by Swing which you have implemented in your code base are however executed on the EDT (as long as Swing called it, not yourself). So in these methods you can query/modify Swing components, but remember to properly transfer in and out any data you give to a Swing component or queried from a Swing component in a thread-safe manner.
Like for example if I create a JButton and add it to a JPanel or JFrame, are these operations running on the EDT by default or no?
The initialization of the objects happens on whatever thread you created them on, and so are the rest of the modifications of the Swing objects (like adding one component to another). I do not know of any Swing components whose public method implementations are wrapped in their own invokeNow() or invokeLater() call, so it's best to assume all portions of the actions happened on whatever thread you called the original methods on.
do I have to explicitly send all my Swing components and methods to run on the EDT by invokingSwingUtilities.invokeLater()
Yes, or invokeNow()
Components will be accessed from within the thread context they are called, wch leads to a problem...
All Swing components (or enough not to matter) MIST be accessed within the context of the Event Dispatching Thread once they have been added to a displayable container (attached to a native peer).
This makes Swing components NOT thread safe and you are responsible for ensuring that they are modified/accessed from the EDT correctly, the framework will NOT do it for you
Take a look at Concurrency in Swing for more details

Why to use SwingUtilities.invokeLater in main method?

After years of Java programming I always used to create my main() methods like this :
public static void main(String[] args)
{
runProgram();
}
But recently I studied some codes from the Web and saw this sometimes instead of the usual main() use above :
public static void main(String[] args)
{
SwingUtilities.invokeLater(new Runnable()
{
public void run()
{
runProgram();
}
});
}
I simply want to know :
Why to use this instead of the usual main() way ? I can't see any difference when I give it a try.
What is the difference between these two ways ?
Thanks for reading me and your answers.
The docs explain why. From Initial Threads
Why does not the initial thread simply create the GUI itself? Because almost all code that creates or interacts with Swing components must run on the event dispatch thread.
and from The Event Dispatch Thread
Some Swing component methods are labelled "thread safe" in the API specification; these can be safely invoked from any thread. All other Swing component methods must be invoked from the event dispatch thread. Programs that ignore this rule may function correctly most of the time, but are subject to unpredictable errors that are difficult to reproduce.
Because the thread "main" started by VM is not the event dispatch thread.
A few Swing components from the API are not thread safe,which means that they may cause some problems like deadlock,So its better to create and update such swing components by using Event dispatcher thread provided by Swing but not from the main thread or any other thread created from main.
While the answers above are all correct, I believe they lack a correct explanation.
Yes, everything that interacts with Swing (creating the UI, updating it, adding new components or layouts, etc.) should be always done on the AWT event-dispatch thread (see this post for more information on the topic).
SwingUtilities.invokeLater() places your code in the FIFO Queue of the event-dispatch thread (EDT), so it will be executed from the EDT whenever it has finished the other tasks it was doing.
Having that said, the EDT should be used exclusively to run Swing-related tasks that are quick to perform (if you block the EDT, you block the whole UI).
There is no point using SwingUtilities.invokeLater() on the main method if you aren't using Swing/AWT (e.g. a JavaFX app or a terminal app).
If you want to perform some tasks that have nothing to do with Swing at all but they're required to start Swing (e.g. starting the Model and Controller in a MVC-like app), you could do it either from the EDT or the Main thread (see this post for a discussion on this topic).

Should Swing GUI application be controlled from Event Dispatcher or main thread?

I've read a few books about Java. In all of them there was at least one chapter teaching GUI programming. In all of them, creating a simple form application was following this logic:
MyFrame.java
public class MyFrame extends JFrame
{
JButton button1;
public MyFrame()
{
button1 = new JButton("Click here.");
}
}
FrameTest.java:
public class FrameTest
{
public static void main(String[] args)
{
MyFrame myFrame = new MyFrame();
myFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
myFrame.setSize(600, 600);
myFrame.setVisible(true);
}
}
Basically, just subclass JFrame to create a form and declare as instance variables the other components and initialize those components in the constructor. And then create another test class, instantiate the frame subclass in that class and call some of its methods to make it visible.
But in concurrency lessons I've learned that we have a main thread which runs main() in every application we create. As far as I know, when we use Swing in order to create GUI applications we have another thread (Event Dispatcher Thread). So if i am not mistaken, in every Swing based GUI application there are at least two threads. This makes every GUI application multithreaded. And in some articles and tutorials that I've read, it says that Swing doesn't support multithreading therefore all GUI components should be created and modified only in Event Dispatcher Thread otherwise Thread Interference and Memory Inconsistency Errors may arise.
Even in the simplest example in Wikipedia (http://en.wikipedia.org/wiki/Swing_%28Java%29), it's made like this via invokeLater method.
So which one is the true approach? Where am I wrong?
ALL interactions with any UI/Swing component MUST be done for within the context of the EDT
When starting an application, you should ensure that you are executing within the EDT BEFORE you try and create/interact with any Swing component.
Simply put, you should use something like...
EventQueue.invokeLater(new Runnable() {
public void run() {
// Now in the event dispatching thread
}
});
If you need to run long running task or perform any blocking task, you should execute it in a separate thread. SwingWorker is a good choice in most cases as it provides some simple mechanisms for re-syncing code to the event dispatching thread.
Take a read through
Initial Thread
Will the real Swing Single Threading Rule please stand up?
So, the short answer is, yes, all Swing based code should be accessed/modified/interacted with from the context of the EDT
So if i am not mistaken, in every Swing based GUI application there
are at least two threads
Yes. One is main thread and other is EDT(Event Dispatch Thread).
This makes every GUI application multithreaded.
Yes. But in that case , the other thread is not interacting with the GUI component.
Swing doesn't support multithreading therefore all GUI components
should be created and modified only in Event Dispatcher Thread
otherwise Thread Interference and Memory Inconsistency Errors may
arise.
Yes , Absolutely true. This means that at a time only one Thread should interact with the given GUI component.
A Swing programmer deals with the following kinds of threads:
Initial threads, the threads that execute initial application code.
The event dispatch thread, where all event-handling code is executed. Most code that interacts with the Swing framework must also execute on this thread.
Worker threads, also known as background threads, where time-consuming background tasks are executed.
The programmer does not need to provide code that explicitly creates
these threads: they are provided by the runtime or the Swing
framework. The programmer's job is to utilize these threads to create
a responsive, maintainable Swing program.

When to use SwingUtilies.invokeAndWait/invokeLater

I read somewhere that for any thread that affects the visuals of the gui it should be ran in the EDT using SwingUtilities.invokeAndWait/invokeLater
For a basic gui, is it necessary to put something like new SwingGUI().setVisible(true); in the line of the EDT using invokeAndWait? Just to display?
Does this count?
The short answer to your question is: yes, even calling setVisible should happen on the EDT. To find out whether the current thread is the EDT, you can use the EventQueue#isDispatchThread method
Some reference links:
Multithreaded Swing Applications
Threads and Swing
Concurrency in Swing
Edit:
after reading the links I provided, it seems some of the articles on the Oracle site are outdated as in they still document you can create Swing components on another thread. There is a stackoverflow question on this which contains some nice answers and links to blogposts and articles about the 'new' policy (new as in a few years old)
Yes, if you touch a Swing object you have to do it on the EDT. In most cases you are already there, but if not, use the SwingUtilities classes. The reason for this is that the Swing classes are not multi-threaded, so you are likely to cause nasty problems if you access it on other threads. And it could be that setVisible() is doing a lot of things under the covers to make something display (like re-laying things out). Better to be safe.
Anything that is called from your
public static void main(String[] agrs) {
directly (without spawning another thread or using invokeLater) is running on the main thread.
Accessing GUI objects with the main thread while they may be being accessed (simultaneously) by the EDT (which is triggered by user input) can cause threading issues. Calling invokeLater causes tasks (runnables) to run on the EDT, preventing simultaneous access by other EDT tasks ie. button presses etc.
If you can be sure the EDT is not busy (before the first window is setVisible(true)) you can access the GUI from the main thread. If you can be sure the EDT has no reference to the component you're working on (it is out of EDT's scope) ie. before it's added to any container, you can access it from main thread without the EDT accessing it simultaneously, as the EDT has no way to reach it.
Everything that access Swing objects should do so via the Event Dispatch Thread (EDT). There is one small exception to this (which I'll mention later). The purpose of the EDT is to process any events that may occur due to IO (mouse and keyboard events). Quite a lot of the time this can mean altering the layout of your GUI. Swing was not developed to be thread-safe, meaning that that if two thread try to modify the same component at the same time then you can end up with a corrupted GUI. Since there is already one known thread to be accessing Swing components (the EDT), no other thread should attempt to modify them or even read their state.
Now, to the exceptional case when you can manipulate Swing objects outside of the EDT. Before any components have become visible it is not possible for IO to be triggering events. Therefore, the main thread can setup a Swing GUI and then set a single JFrame to be visible. Since there is now a visible frame IO events can occur and the main thread should not try to modify any more Swing components. The should only use this option to get a GUI started, and really only with toy problems.
What I'm saying is that the following is fine and won't cause problems if you're just playing around with stuff.
public static void main(String[] args) {
// create components
JFrame f = new JFrame();
...
// do layout and other bits of setup
// show gui to user
f.setVisible(true);
}

Categories