I am trying to use a JProgressBar, but my code is really slow and almost crash each time I run my application. At the beginning, the progress bar is set to indeterminate, then when you hit the button "Stop" (in my program, when the background task is done), the progress bar is set to determinate and start to fill quickly.
How can I improve the efficiency of this code ? I didn't find a lot of resources on indeterminate JProgressBar.
Here is my code :
public class test extends JFrame {
static JFrame f;
static JProgressBar b;
public static void main(String[] args) {
f = new JFrame("ProgressBar demo");
f.setLayout(new BorderLayout());
JPanel p = new JPanel();
b = new JProgressBar();
b.setValue(0);
b.setStringPainted(true);
b.setIndeterminate(true);
p.add(b);
f.add(p, BorderLayout.NORTH);
JButton button = new JButton("stop");
button.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent arg0) {
b.setIndeterminate(false);
fill();
}
});
f.add(button, BorderLayout.SOUTH);
f.setSize(500, 500);
f.setVisible(true);
//fill();
}
// function to increase progress
public static void fill() {
int i = 0;
try {
while (i <= 100) {
b.setValue(i + 10);
Thread.sleep(1000);
i += 20;
}
} catch (Exception e) {}
}
}