tags:

views:

55

answers:

3

How can I perform action in background at program start? I would expect some kind of onLoad event for this purpose. Just to be clear: Load ui. Do some stuff and load some more UI based on result of my event.

+1  A: 

I don't think there's any specific API for "do stuff in background at start". But you can just create a new Thread, which is the standard way of doing background stuff in Java.

If you're new to threads and concurrent programming in general, you may take some time to learn what you need. A good start is the Java tutorial:

http://java.sun.com/docs/books/tutorial/essential/concurrency/

sleske
not really new to threading, but it seems to me it is a bad idea to touch UI code from a different thread, which led me to believe there would be a construct readdy slightly more advanced than a thread
Esben Skov Pedersen
Java Concurrency in Practice- by Brian Goetz is an excellent book which goes into higher level concurrency abstractions. It has a section specific to GUIs as well.
Luhar
+3  A: 

Have a look at the SwingWorker. Swing is single threaded so any background processing needs to be done from a seperate thread to avoid blocking the swing (event dispatch) thread.

There also no onLoad type functionality available so you'll need to startup the worker yourself when you initialise your gui.

There are utility method in EventQueue class, invokeLater() and invokeNow() which can be used to update the gui from a different thread. They allow you to specify code to be run on the event dispatch thread.

objects
+2  A: 

To add to objects' answer above:

If you are using a UI based application, you should use the SwingWorker threads to do any non-GUI related work. All Swing tasks for example, run on the Event Dispatch Thread (EDT). If you want to run code on the EDT, you should use the SwingUtilities methods. invokeLater() adds the task to the current queue of tasks on the EDT, and invokeAndWait() runs the task and blocks until completion.

If you want to make sure that something is not running on the EDT, you can use the SwingUtilities.isEventDispatchThread() call to determine if the current thread is the EDT.

If you are initialising your GUI from the main() method of your app, make sure that any calls to make GUI components visible, or in general, any GUI interaction runs on the EDT.

Luhar