Reputation: 37
i have a problem with my loading bar. I want the loading bar to appear on my panel before it starts loading images. But what happens is the loading bar appears after the images are loaded. Here is my code.
private void initializeProgram(Dimension size){
screenSize = size;
//load class
frame = new JFrame();
homePanel = new HomePanel(size);
loadingBar = new LoadingBar(new Dimension(500, 30));
//initialize class
frame.getContentPane().setLayout(null);
frame.setSize(600, 600);
frame.setVisible(true);
frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
frame.getContentPane().add(loadingBar);
loadingBar.setLocation(50, 50);
int objectCount;
objectCount = homePanel.getImageCount(); //i have 15 images
loadingBar.setMaxValue(objectCount); //maximum value set to 15
loadingBar.repaint(); //i tried to repaint hoping to appear
frame.getContentPane().repaint(); //here too
for(int i = 0; i<objectCount; i++){
homePanel.loadImage();
loadingBar.setValue(i+1); //moves the loading bar as a sign of
loadingBar.repaint(); //progress, and i want it to repaint
}
System.out.println("DONE!");
//load fonts
//load sounds
}
inside my homePanel.loadImage() is this:
public void loadImage(){
try{
image[imageLoadedCount] = ImageIO.read(new File(imagePath[imageLoadedCount]));
}
catch(IOException ex){
ex.printStackTrace();
}
imageLoadedCount++;
}
When i try to run it, the JFrame is blank, after few seconds the loading bar will appear together with the "DONE!" print on output.
Upvotes: 0
Views: 66
Reputation: 13427
Your problem is probably caused by loading the images on the EDT (event dispatch thread). This blocks the rest of the GUI.
For tasks that take time, like loading images, use a SwingWorker
. This created a new thread where your task is executed and you can also query the thread (e.g., for progress) while it is running. Running long tasks on a background thread leaves the EDT free to update quickly.
Note: make sure you initialize the GUI in an initial thread.
Upvotes: 1
Reputation: 324118
Don't use a null layout. Swing was designed to be used with Layout Managers.
The frame.setVisible(true)
statement should be executed AFTER
all the components have been added to the frame and its child panels.
Upvotes: 1