I searched for this question and I found several documentation but they are too complicated to understand for me.
I just want simply to make progress bar works during an activity not after that.
At the sample codes I provided, the progress bar works after the run method done, not during that. how can I change this code to progress bar is being updated when the run method is working?
I think I have to create a new thread to handle the long-running method but I don't know how to do that?
public class Gui extends JFrame {
private JProgressBar progressBar;
private JButton button;
public Gui() throws HeadlessException {
super("Progress bar");
setSize(500, 100);
setDefaultCloseOperation(EXIT_ON_CLOSE);
setLayout(new FlowLayout());
add(resPan());
}
private JPanel resPan() {
JPanel resPan = new JPanel(new FlowLayout(FlowLayout.CENTER));
resPan.setPreferredSize(new Dimension(500, 100));
progressBar = new JProgressBar();
progressBar.setPreferredSize(new Dimension(180, 40));
button = new JButton("Action");
button.setPreferredSize(new Dimension(80, 40));
button.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
progressBar.setIndeterminate(true);
run();
}
});
resPan.add(button);
resPan.add(progressBar);
return resPan;
}
private void run() {
try {
Thread.sleep(4000);
//progressBar.setIndeterminate(false);
} catch (InterruptedException e) {
e.printStackTrace();
}
}}