简体   繁体   中英

How to preload Swing components

I know this is sort of a vague question, but I will try to make it as clear as possible. When my Java app launches for the first time, it does some checking to see if files and directories exist and checks for an internet connection.

The app then allows the user to move on to the dashboard, which requires loading and adding many Swing components to the Background Panel. This takes time.

I was wondering how I could make it so that during the loading process at the start, the app loads all of the Swing components Images etc. so that they appear instantly when the user executes the command to do so.

I can load all of the components like this:

JButton = new JButton("blah"); 

but I'm not sure that's enough to make the components appear instantly, wouldn't adding several image filled Swing components at the same time still lag the UI thread, even if it was already "loaded" as seen above?

Thanks!

on the components use

setVisible(false)

for example

public class myParentPanel extends JPanel{
     public myParentPanel{

     //add all the child components
     //Do what ever takes along time
     setVisible(false); //this then makes in invisible but still 
                        //allows all the set up code to run
     }

     public void showParent(){
         setVisible(true);
         invalidate();
     }
}

and then create a method to make them visible when required. Hence all your setting in the constructors ca be called then when you call your method say:

drawWindow()

it then only has to call setVisible(true) and invalidate the screen to call their painting methods :).

An advancement on this would be to * run your setups ie your checking and loading the panels methods on a separate threads *so you don't have to wait for a sequential loading. So on your loading you may to use an anonymous class

 SwingUtilities.invokeLater(new Runnable(){ public void run(){

     //do my display set up

}});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM