I am currently self-studying Java. I've been trying different things like JRadioButton
s, JcomboBox
es etc. Now, I'm trying to use JProgressBar
s but it doesn't seem to work properly.
Relevant piece of code:
JProgressBar progress;
JButton button; //Fields of the class
progress=new JProgressBar(JProgressBar.HORIZONTAL,0,100);
button=new JButton("Done"); //Done from methods
progress.setValue(0);
progress.setStringPainted(true);
progress.setBorderPainted(true); //Also done from methods
button.addActionListener(this); //Also done from methods
When button
is clicked, I want to show the JProgressBar go from 0% to 100%. Here is the relevant portion of the actionPerformed
method:
public void actionPerformed(ActionEvent e)
{
for(int i=0;i<=progress.getMaximum();i++)
{
progress.setValue(i);
/*try{
Thread.sleep(10);
}catch(InterruptedException ex)
{
System.err.println("An error occured:"+ex);
ex.printStackTrace();
}*/
}
progress.setValue(progress.getMinimum());
}
I've added both progress
and button
into a JPanel and the panel into a JFrame on which I use setVisible(true);
.
The problem here is, whenever I press the JButton button
, the JProgressBar progress
does not go from 0% to 100%. Instead, nothing happens. If I uncomment the try...catch
block, and then press button
, the program "freezes" for a moment and then continues. This time too, The JProgressBar stays at 0% and I never see it moving. I've also tried a repaint();
just after the try...catch
block but the same thing happened.
I've tried adding
System.out.println(i+"");
inside the for
loop in actionPerformed
and this printed numbers 0 to 100 in the terminal. So, I'm sure that the loop runs.
How can I solve this problem?