Reputation: 34735
I had developed a Swing GUI which contains 12 JPanel
s. Initially, all the JPanel
s 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:
JPanel
s 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 JPanel
s showed at a time based on the button on which use has clicked. Now when I have seperated those 12 JPanel
s 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?Upvotes: 3
Views: 203
Reputation: 9426
Current recommendeded practice is that all calls to swing components are done on the EDT. See Java: Swing Libraries & Thread Safety and 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.
Upvotes: 0
Reputation: 39485
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.
Upvotes: 0
Reputation: 819
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.
Upvotes: 1