views:

64

answers:

4

I had developed a Swing GUI which contains 12 JPanels. Initially, all the JPanels code was written in the main JFrame class code. As a result, the code became too long (10,000+ lines).

Now I want to refactor the code to break the code into 13 classes (12 classes each for one JPanel and 1 class for the main JFrame)instead of 1 class carrying all the code.

But I have some confusions which is as follows:

  1. Initially those 12 JPanels were set on a "Card" JPanel and the layout of the "Card" JPanel was set to CardLayout so that only 1 JPanel out of those 12 JPanels showed at a time based on the button on which use has clicked. Now when I have seperated those 12 JPanels from the MainJForm and implemented each of them into its own class, I think I need to instantiate a corresponding JPanel first whenever a user clicks on the button. So, would it better to do this heavy task on the EDT (Event Dispath Thread). If no, then Will it work to make a instance of the JPanel in SwingWorker thread and pass a ref. to EDT?
+1  A: 

You can instatiate your panels exactly in the same manner as was done when they were all in one class. So if the previous implementation created all the objects on frame instantiation, you can just instantiate your 12 panel objects likewise. If this had been done as soon as the panel showed on button click, do it the same way.

The question where the code is placed should have no impact on the question when it is executed in this case, at least as long as there haven't been issues with that before (ui hangs when switching panels on button click).

Of course, you can first create the panel that initially shows and then use a swingworker to create the other ones so the first one shows instantly and the other ones are available as soon as the button is clicked without having to instantiate them then first. Just make sure you take care to place calls that change the currently showing ui (like adding instantiated panels to the frame) in the EDT.

Mathias Weyel
A: 

Constructing the 12 instances of JPanel in the EDT shouldn't be a concern. I would go ahead and make them that way. This will make your code much easier to read. Be wary of premature optimization. I would only move to optimize performance if you experience performance issues.

akf
A: 

Current recommendeded practice is that all calls to swing components are done on the EDT. See http://stackoverflow.com/questions/182316/java-swing-libraries-thread-safety and http://stackoverflow.com/questions/491323/is-it-safe-to-construct-swing-awt-widgets-not-on-the-event-dispatch-thread.

If (as part of their initialisation) any of those panels require something that could take a long time (such as disc or network access), those calls should be delegated to another thread, but not any of the changes to the swing component itself.

Ash
A: 

You might look at any of the SwingSet demos, such as SwingSet2 or SwingSet3.

trashgod