I have written code using swing libs, that when added an actionlistener, won't update a progressBar.
Without a button and action listener, it works great. How to force a progressBar update as simply and cleanly as possible? Appended code is an easy to understand example that sums up my problem. If you comment out an ActionPerformed method and execute the program from main, it works just fine.
Do not just paste code whithout explaining.
ps.: I have seen this: swing progressBar threading
public class Okno {
private JProgressBar progressBar = new JProgressBar(0,306);
JFrame f = new JFrame("JProgressBar Sample");
JButton b = new JButton("start");
ActionListener a = new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
barupdate();
}
};
private void barupdate(){
for(int p = 1; p<308;p=p+2){
System.out.println(p);
progressBar.setValue(p);
try {
Thread.sleep(50);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
private Okno(){
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
progressBar.setStringPainted(true);
f.add(progressBar, BorderLayout.SOUTH);
f.add(b, BorderLayout.NORTH);
b.addActionListener(a);
f.setSize(300, 300);
f.setVisible(true);
}
public static void main(String[] args) {
Okno okno = new Okno();
}
}