2

I just need some advice from people more experimented about Threads and Swing.

The inititialization of the GUI of my program takes a while, so I'm initializing it in a second Thread with a SwingWorker, while I use the EDT to make the user wait, this way :

private static class Initializer extends SwingWorker<Void,Integer> {
    @Override
    protected Void doInBackground() throws Exception {
        gui = new GUI(getThemeElement("laf"));
        initialize();
        return null;
    }
    @Override
    public void done() {
        gui.setVisible(true);
        Loading.stop();//consider that "Loading" is a static JProgressBar
    }
    @Override
    protected void process(List<Integer> L) {
        Loading.setValue(L.get(L.size()-1));//consider that "Loading" is a static JProgressBar
    }

}

I thought it was a good idea because I prepare the GUI in background, and use the EDT to display it in the end. But someone told me to never instantiate Swing elements outside the EDT. So, what is the best way to prepare a user interface without locking the EDT ?

Thank you for your advice !

Sharcoux
  • 5,546
  • 7
  • 45
  • 78
  • this could help: http://docs.oracle.com/javase/tutorial/uiswing/concurrency/ – Dylan Meeus Dec 08 '13 at 13:56
  • Ok, they explain precisely that I shouldn't do what I'm doing, but it doesn't help me a lot to understand what I should do instead ^^. Thanks for the link anyway. – Sharcoux Dec 08 '13 at 14:25
  • 3
    Measure what takes so much time in initializing the GUI. If you're, for example, reading a bunch of files while initializing it, then do that in a background thread. If everything is GUI-based, then try to only initialize the components that you need to display, and initialize all the other ones on demand (for example, if you have a CardLayout with 9 hidden panels, you just need to initialize the one that must be visible from the start). – JB Nizet Dec 08 '13 at 14:33
  • Ok, I see. I will try this approach. Thank you – Sharcoux Dec 08 '13 at 14:36
  • 2
    In addition to @JBNizet's suggestions, you might try the approach suggested [here](http://stackoverflow.com/a/20443625/230513). – trashgod Dec 08 '13 at 18:43
  • Yes, thank you. I'm trying both approach, but it's not that easy to change a synchronous system that loads everything and then is fully ready to use, into a system where you don't know exactly what is already loaded/accessible. I'll probably come back soon for help. – Sharcoux Dec 09 '13 at 08:12

0 Answers0