Reputation: 1163
Hi. I'm preparing a form in java where I want to show a progress bar from value 1 to 5 in an interval of 0.5 seconds each, but, in my code, the progress bar jumps directly from 1 to 5 after 2.5 secs .. Please help me with the code...
public class cafee extends JFrame implements ActionListener {
JProgressBar pr1;
JButton b1;
public cafee() {
setLayout(new FlowLayout());
pr1 = new JProgressBar();
pr1.setSize(10, 1);
pr1.setForeground(Color.blue);
pr1.setMinimum(0);
pr1.setMaximum(5);
pr1.setValue(0);
pr1.setVisible(true);
b1 = new JButton();
b1.setVisible(true);
add(pr1);
add(b1);
b1.addActionListener(this);
}
public void actionPerformed(ActionEvent ae) {
if (ae.getSource() == b1) {
for (int a = 1; a <= 5; a++) {
try {
pr1.setValue(a);
Thread.sleep(500);
} catch (Exception e) {
}
}
}
}
public static void main(String[] args) {
cafee caf = new cafee();
caf.setVisible(true);
caf.setSize(500, 500);
}
}
Upvotes: 0
Views: 108
Reputation: 691625
If you sleep in the event dispatch thread (EDT), you're blocking it, and thus preventing all the other event handling and painting methods to occur. JProgressBar
is useful to display the progress of some task running in a separate background thread.
Use a SwingWorker
. Its api doc contains an easy to understand example.
Upvotes: 1