package com.java.myapp;
import java.awt.EventQueue;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JProgressBar;
import javax.swing.SwingWorker;
public class MyForm extends JFrame {
private JProgressBar progressBar;
private JButton btnStart;
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
MyForm form = new MyForm();
form.setVisible(true);
}
});
}
public MyForm() {
// Create Form Frame
super("ThaiCreate.Com Java GUI Tutorial");
setSize(525, 270);
setLocation(500, 280);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
getContentPane().setLayout(null);
// Label Title
final JLabel lblTitle = new JLabel("ProgressBar", JLabel.CENTER);
lblTitle.setBounds(73, 24, 370, 14);
getContentPane().add(lblTitle);
// ProgressBar
progressBar = new JProgressBar();
progressBar.setStringPainted(true);
progressBar.setMinimum(0);
progressBar.setMaximum(100);
progressBar.setBounds(163, 80, 190, 20);
getContentPane().add(progressBar);
// Button Start
btnStart = new JButton("Start");
btnStart.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
btnStart.setEnabled(false);
EventQueue.invokeLater(new Runnable() {
@Override
public void run() {
new BackgroundWorker().execute();
}
});
}
});
btnStart.setBounds(209, 144, 100, 23);
getContentPane().add(btnStart);
}
public class BackgroundWorker extends SwingWorker<Void, Void> {
public BackgroundWorker() {
addPropertyChangeListener(new PropertyChangeListener() {
@Override
public void propertyChange(PropertyChangeEvent evt) {
progressBar.setValue(getProgress());
}
});
}
@Override
protected void done() {
btnStart.setEnabled(true);
}
protected Void doInBackground() throws Exception {
for (int index = 0; index <= 100; index++) {
setProgress(index);
Thread.sleep(100);
/**
* Do work
* Do work
* Do work
*/
}
return null;
}
}
}