In the previous section, you have seen how to display a progress dialog in a console application. In this section, you’ll learn how to make a progress dialog in a Swing UI application.
We want create a simple UI program as shown in the illustration below:
Here is the code to create the above UI:
1. public class DemoSimpleUI {
2. public static void main(String[] args) {
3. try {
final JFrame frame = new JFrame("DemoSimpleUI");
4.
5. JButton button = new JButton("Start");
6. final JTextArea textArea = new JTextArea();
7.
8. button.addActionListener(new ActionListener() {
9. public void actionPerformed(ActionEvent e) {
10. new Thread() {
11. public void run() {
12. int range = 10;
13. ProgressDialog progressDialog = new ProgressDialog(frame, "Progress");
14. progressDialog.beginTask("Number Counting", range, true);
15.
16. for(int i=0; i<range; i++) {
17. if(progressDialog.isCanceled()) {
18. textArea.append("CANCELED.\n\n");
19. break;
20. }
21.
22. //JTextArea.append() is thread-safe.
23. textArea.append(i + " of " + range + "\n");
24. progressDialog.worked(1);
25. try {
26. Thread.sleep(500);
27. } catch (InterruptedException e) {
28. e.printStackTrace();
29. }
30. }
31.
32. }
33. }.start();
34. }
35. });
36.
37. frame.getContentPane().setLayout(new BorderLayout());
38. frame.getContentPane().add(button, BorderLayout.NORTH);
39. frame.getContentPane().add(new JScrollPane(textArea), BorderLayout.CENTER);
40.
41. frame.setSize(600, 400);
42. frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
43. frame.setVisible(true);
44. }
45. }
When the button is clicked, a new thread is started to execute the number counting task. You might notice that the code used to show and update the progress dialog is essentially the same as that we used in last section. One exception is that we set the parent component of the dialog to the frame:
ProgressDialog progressDialog = new ProgressDialog(frame, "Progress");
When the operation is in progress, the progress dialog blocks the user to access the frame. This behavior is highly desired in most of scenarios. If you need to modify this behavior, refer to the late sections.