What I want to do is to show a new panel with a progress bar while the process takes place.
My code is as follows:
case "GoButton":
cards.show(this, "pp");
this.test();
cards.show(this, "panel1");
break;
That is in a actionPerformed
method
but when I run the program it just ignores the first cards.show
, it executes the test
code and then it executes the second cards.show
I also provide you the rest of the code in case you need it
public CreatePanel(JFrame frame) {
ext = new ArrayList<>();
files = new ArrayList<>();
this.mainWindow = frame;
this.setSize(256, 256);
cards = new CardLayout();
this.setLayout(cards);
panel1 = new JPanel(null);
createPanel1(panel1);
this.add(panel1, "panel1");
panel2 = new JPanel(null);
createPanel2(panel2);
this.add(panel2, "panel2");
panel3 = new JPanel(null);
createPanel3(panel3);
this.add(panel3, "pp");
cards.show(this, "panel1");
}
public class ProgressPanel {
private static JPanel panel;
private static JProgressBar progressBar;
private static int progress;
public static JPanel createProgressPanel(){
ProgressPanel.panel = new JPanel(null);
ProgressPanel.initPanel();
return ProgressPanel.panel;
}
private static void initPanel(){
panel.setLayout(new GridBagLayout());
GridBagConstraints c = new GridBagConstraints();
progressBar = new JProgressBar(0, 100);
progressBar.setValue(progress);
progressBar.setStringPainted(true);
panel.add(progressBar, c);
}
public static void updateProgress(int x){
ProgressPanel.progress += x;
}
public void resetProgress(){
this.progress = 0;
}
}
Your problem likely likes here: this.test();
. I'm betting that this method calls long running code, and since it's being called on the Swing event thread, it's tying up this thread preventing your GUI from updating itself and in fact completely freezing the GUI. Solution: use a SwingWorker or other background thread for long-running tasks. Please have a look at Concurrency in Swing.
Note that if you do use a SwingWorker, you'll need to use either a PropertyChangeListener or the done()
method to be notified when the background thread has completed and that it's time to call cards.show(this, "panel1");
. Myself, I'd add a PropertyChangeListener to my SwingWorker, since this way, I could both listen for the completion of the listener, and also could listen for changes in the worker's progress property, and then use that value to set my JProgressBar's value.