Calling event dispatch thread

I have a main class which extends JFrame.

I add panels to this instance of frame which consist of JTable and other Swing components.

In this main class in the "public static void main", I set swing event dispatch thread.

I add panels to this instance frame, and initiate:



All fine up to here.

Now, for JTable it has a listener and when a row is clicked it opens up a new instance of a class InfoDialog.

In this InfoDialog I add Swing components as usual.

I have another dispatch thread in JDialog like this:

class InfoDialog  {
    JDialog jd;
    public void initGUI() {
    SwingUtilities.invokeLater(new Runnable() {
        public void run() {
                 jd = new JDialog();

Putting the event dispatch thread solves the errors I'm getting (probably because its blocking the current thread previosuly), and my question is, is this the right way to do it?

Thanks for any advice.


Basically, you should only be creating and interacting with the dialog (and all other UI components) from within the context of the Event Dispatching Thread.

You can (at some extent), ensure this by calling EventQueue.invokeLater from your main method to start with. This ensures that most of the UI is already been called from within the context of the EDT.

public static void main(String args[]) {
    EventQueue.invokeLater(new Runnable() {
        public void run() {
            //...Your UI code here...

It should be safe to assume that you are within the EDT at all other times. It should be the responsibility of the caller to ensure this, not your components. I often create "safe" factory methods to make it easier to construct some UI components (things like progress indicators for example) which are designed and documented to be thread safe.

Check out Concurrency in Swing and Initial Threads for more details.

Need Your Help

Can I avoid float elements shifting when I resize my browser?

html css css-float

I am new to the world of coding as well as CSS and have noticed that when I resize my browser, all my float elements move to say the right and the user is forced to scroll horizontally to view say ...

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.