심플하면서도 뭔가 ... 세련되고 이쁜 ... 그런것을 원한다. 그러기 쉽지 않다
다음 예제들을 비교해보자
출처 : [Java 기초 040] - AWT, Swing, JFrame, 진행바, JProgressBar,JList, DefaultListModel, JTree, JTable
JProgressBar 에 관한 소스만 원했는데
JProgressBar 외 JList, DefaultListModel, JTree, JTable 등등이 함께 있길래 그중 JProgressBar 에 관한 소스만 퍼왔다.
JFrameTest04.java
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
|
import java.awt.FlowLayout;
import javax.swing.JFrame;
import javax.swing.JProgressBar;
class JFrameTest04 extends JFrame {
JProgressBar progress;
/*
* JProgressBar 클래스 특징 1.오랜 시간이 걸리는 작업을 할때 일의 진행상황을 시각적으로 표현하기 위한 용도로 사용되는
* 클래스이다.
*/
public JFrameTest04() {
setLayout(new FlowLayout());// 배치관리자 설정
progress = new JProgressBar();
// 최소값이 0,최대값이 100까지 표시
// progress.setValue(0);//0부터 시작.시작 지점값을
// 표시
progress.setStringPainted(true);
// true로 설정하면 현재 진행상황을 %로 표시함.
add(progress);// 스윙 프레임윈도우에 프로그래스바
// 배치
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setSize(300, 150);
setVisible(true);
progress_start();// progress_start()메서드를
// 호출
}// 생성자 정의
public void progress_start() {
int i;
try {
for (i = 51; i <= 100; i++) {
progress.setValue(i);
Thread.sleep(37);// 밀리세컨드 단위로
// 지연시간을 설정.
}
} catch (InterruptedException ie) {
ie.printStackTrace();
}
}// progress_start()끝
}
public class SwingTest04 {
public static void main(String[] args) {
new JFrameTest04();// 생성자를 호출
}
}
|
cs |
시각적 효과를 보여주기 위해 progress_start() 를 만들어두었다. 좋다
다음은 단순히 ProgressBar 에 대한 짧고 간결한 예제
출처 : Progress bar Sample : ProgressBar « Swing JFC « Java
ProgressSample.java
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
|
import java.awt.BorderLayout;
import java.awt.Container;
import javax.swing.BorderFactory;
import javax.swing.JFrame;
import javax.swing.JProgressBar;
import javax.swing.border.Border;
public class ProgressSample {
public static void main(String args[]) {
JFrame f = new JFrame("JProgressBar Sample");
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
Container content = f.getContentPane();
JProgressBar progressBar = new JProgressBar();
progressBar.setValue(25);
progressBar.setStringPainted(true);
Border border = BorderFactory.createTitledBorder("Reading...");
progressBar.setBorder(border);
content.add(progressBar, BorderLayout.NORTH);
f.setSize(300, 100);
f.setVisible(true);
}
}
|
cs |
Border 로 감싸고 "Reading..." 이라는 메시지를 찍어줬을 뿐인데 ...
뭐지? 이 느낌은?
좀더 들쳐보고 싶어졌다
http://www.java2s.com 에는 다양한 예제들이 있었다
위에서 언급한 출처 Progress bar Sample : ProgressBar « Swing JFC « Java 내용을 보면
Java / Swing JFC / ProgressBar / Progress bar Sample
이런식으로 카테고리가 세분화 되어 있었다
그중 ProgressBar 를 들여다 보았다
1. Create a ProgressBar
2. Create a horizontal progress bar
3. Create a vertical progress bar
4. Creating a JProgressBar Component with an Unknown Maximum
5. Set all the values at once by using the model
6. Listening for Value Changes in a JProgressBar Component
7. Displaying the Percentage Done on a JProgressBar Component
8. Getting and Setting the Values of a JProgressBar Component
9. ProgressBar Demo: long task
9개의 개시글이 있었다
좋아 ... 하나 하나 까뒤집어 주겠어
1.Create a ProgressBar
Main.java
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
|
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JProgressBar;
public class Main extends JFrame {
JProgressBar current = new JProgressBar(0, 2000);
int num = 0;
public Main() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel pane = new JPanel();
current.setValue(0);
current.setStringPainted(true);
pane.add(current);
setContentPane(pane);
}
public void iterate() {
while (num < 2000) {
current.setValue(num);
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
}
num += 95;
}
}
public static void main(String[] arguments) {
Main frame = new Main();
frame.pack();
frame.setVisible(true);
frame.iterate();
}
}
|
cs |
2.Create a horizontal progress bar
해석하면 수평 진행률 막대 만들기
|
1
2
3
4
5
6
7
8
9
10
|
import javax.swing.JProgressBar;
public class Main {
public static void main(String[] argv) throws Exception {
int minimum = 0;
int maximum = 100;
JProgressBar progress = new JProgressBar(minimum, maximum);
}
}
|
cs |
3.Create a vertical progress bar
해석하면 수직 진행 막대 만들기
|
1
2
3
4
5
6
7
8
9
|
import javax.swing.JProgressBar;
public class Main {
public static void main(String[] argv) throws Exception {
int minimum = 0;
int maximum = 100;
JProgressBar progress = new JProgressBar(JProgressBar.VERTICAL, minimum, maximum);
}
}
|
cs |
4.Creating a JProgressBar Component with an Unknown Maximum
불명 한 최대치를 가지는 JProgressBar의 작성
|
1
2
3
4
5
6
7
8
9
10
11
12
13
|
import javax.swing.JProgressBar;
public class Main {
public static void main(String[] argv) throws Exception {
// Create a horizontal progress bar
int min = 0;
int max = 100;
JProgressBar progress = new JProgressBar(min, max);
// Play animation
progress.setIndeterminate(true);
}
}
|
cs |
5.Set all the values at once by using the model
모델을 사용하여 모든 값을 한 번에 설정하십시오.
|
1
2
3
4
5
6
7
8
9
10
11
12
13
|
import javax.swing.JSlider;
public class Main {
public static void main(String[] argv) throws Exception {
JSlider slider = new JSlider();
int newValue = 2;
int newExtent = 10;
int newMin = 0;
int newMax = 10;
slider.getModel().setRangeProperties(newValue, newExtent, newMin, newMax, false);
}
}
|
cs |
예제를 보니 ... Slider ;; 뭔가 이건 링크가 잘못되었다
6.Listening for Value Changes in a JProgressBar Component
JProgressBar 구성 요소의 값 변경 수신 대기
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
|
import javax.swing.JProgressBar;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;
public class Main {
public static void main(String[] argv) throws Exception {
int minimum = 0;
int maximum = 100;
JProgressBar progress = new JProgressBar(minimum, maximum);
progress.addChangeListener(new ChangeListener() {
public void stateChanged(ChangeEvent evt) {
JProgressBar comp = (JProgressBar) evt.getSource();
int value = comp.getValue();
int min = comp.getMinimum();
int max = comp.getMaximum();
}
});
}
}
|
cs |
7.Displaying the Percentage Done on a JProgressBar Component
JProgressBar 구성 요소에 대한 백분율 표시
|
1
2
3
4
5
6
7
8
9
10
11
12
13
|
import javax.swing.JProgressBar;
public class Main {
public static void main(String[] argv) throws Exception {
int minimum = 0;
int maximum = 100;
JProgressBar progress = new JProgressBar(minimum, maximum);
// Overlay a string showing the percentage done
progress.setStringPainted(true);
}
}
|
cs |
8.Getting and Setting the Values of a JProgressBar Component
JProgressBar 구성 요소 값 가져 오기 및 설정
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
|
import javax.swing.JProgressBar;
public class Main {
public static void main(String[] argv) throws Exception {
int minimum = 0;
int maximum = 100;
JProgressBar progress = new JProgressBar(minimum, maximum);
// Get the current value
int value = progress.getValue();
// Get the minimum value
int min = progress.getMinimum();
// Get the maximum value
int max = progress.getMaximum();
// Change the minimum value
int newMin = 0;
progress.setMinimum(newMin);
// Change the maximum value
int newMax = 256;
progress.setMaximum(newMax);
// Set the value; the new value will be forced into the bar's range
int newValue = 33;
progress.setValue(newValue);
}
}
|
cs |
9.ProgressBar Demo: long task
ProgressBar 데모 : 긴 작업
ProgressBarDemo.java
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
|
/* From http://java.sun.com/docs/books/tutorial/index.html */
/*
* Copyright (c) 2006 Sun Microsystems, Inc. All Rights Reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* -Redistribution of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
*
* -Redistribution in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* Neither the name of Sun Microsystems, Inc. or the names of contributors may
* be used to endorse or promote products derived from this software without
* specific prior written permission.
*
* This software is provided "AS IS," without a warranty of any kind. ALL
* EXPRESS OR IMPLIED CONDITIONS, REPRESENTATIONS AND WARRANTIES, INCLUDING
* ANY IMPLIED WARRANTY OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE
* OR NON-INFRINGEMENT, ARE HEREBY EXCLUDED. SUN MIDROSYSTEMS, INC. ("SUN")
* AND ITS LICENSORS SHALL NOT BE LIABLE FOR ANY DAMAGES SUFFERED BY LICENSEE
* AS A RESULT OF USING, MODIFYING OR DISTRIBUTING THIS SOFTWARE OR ITS
* DERIVATIVES. IN NO EVENT WILL SUN OR ITS LICENSORS BE LIABLE FOR ANY LOST
* REVENUE, PROFIT OR DATA, OR FOR DIRECT, INDIRECT, SPECIAL, CONSEQUENTIAL,
* INCIDENTAL OR PUNITIVE DAMAGES, HOWEVER CAUSED AND REGARDLESS OF THE THEORY
* OF LIABILITY, ARISING OUT OF THE USE OF OR INABILITY TO USE THIS SOFTWARE,
* EVEN IF SUN HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.
*
* You acknowledge that this software is not designed, licensed or intended
* for use in the design, construction, operation or maintenance of any
* nuclear facility.
*/
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
/*
* ProgressBarDemo.java is a 1.4 application that requires these files:
* LongTask.java
* SwingWorker.java
*/
public class ProgressBarDemo extends JPanel implements ActionListener {
public final static int ONE_SECOND = 1000;
private JProgressBar progressBar;
private Timer timer;
private JButton startButton;
private LongTask task;
private JTextArea taskOutput;
private String newline = "\n";
public ProgressBarDemo() {
super(new BorderLayout());
task = new LongTask();
// Create the demo's UI.
startButton = new JButton("Start");
startButton.setActionCommand("start");
startButton.addActionListener(this);
progressBar = new JProgressBar(0, task.getLengthOfTask());
progressBar.setValue(0);
progressBar.setStringPainted(true);
taskOutput = new JTextArea(5, 20);
taskOutput.setMargin(new Insets(5, 5, 5, 5));
taskOutput.setEditable(false);
taskOutput.setCursor(null); // inherit the panel's cursor
// see bug 4851758
JPanel panel = new JPanel();
panel.add(startButton);
panel.add(progressBar);
add(panel, BorderLayout.PAGE_START);
add(new JScrollPane(taskOutput), BorderLayout.CENTER);
setBorder(BorderFactory.createEmptyBorder(20, 20, 20, 20));
// Create a timer.
timer = new Timer(ONE_SECOND, new ActionListener() {
public void actionPerformed(ActionEvent evt) {
progressBar.setValue(task.getCurrent());
String s = task.getMessage();
if (s != null) {
taskOutput.append(s + newline);
taskOutput.setCaretPosition(taskOutput.getDocument().getLength());
}
if (task.isDone()) {
Toolkit.getDefaultToolkit().beep();
timer.stop();
startButton.setEnabled(true);
setCursor(null); // turn off the wait cursor
progressBar.setValue(progressBar.getMinimum());
}
}
});
}
/**
* Called when the user presses the start button.
*/
public void actionPerformed(ActionEvent evt) {
startButton.setEnabled(false);
setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR));
task.go();
timer.start();
}
/**
* Create the GUI and show it. For thread safety, this method should be invoked
* from the event-dispatching thread.
*/
private static void createAndShowGUI() {
// Make sure we have nice window decorations.
JFrame.setDefaultLookAndFeelDecorated(true);
// Create and set up the window.
JFrame frame = new JFrame("ProgressBarDemo");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
// Create and set up the content pane.
JComponent newContentPane = new ProgressBarDemo();
newContentPane.setOpaque(true); // content panes must be opaque
frame.setContentPane(newContentPane);
// Display the window.
frame.pack();
frame.setVisible(true);
}
public static void main(String[] args) {
// Schedule a job for the event-dispatching thread:
// creating and showing this application's GUI.
javax.swing.SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGUI();
}
});
}
}
class LongTask {
private int lengthOfTask;
private int current = 0;
private boolean done = false;
private boolean canceled = false;
private String statMessage;
public LongTask() {
// Compute length of task...
// In a real program, this would figure out
// the number of bytes to read or whatever.
lengthOfTask = 1000;
}
/**
* Called from ProgressBarDemo to start the task.
*/
public void go() {
final SwingWorker worker = new SwingWorker() {
public Object construct() {
current = 0;
done = false;
canceled = false;
statMessage = null;
return new ActualTask();
}
};
worker.start();
}
/**
* Called from ProgressBarDemo to find out how much work needs to be done.
*/
public int getLengthOfTask() {
return lengthOfTask;
}
/**
* Called from ProgressBarDemo to find out how much has been done.
*/
public int getCurrent() {
return current;
}
public void stop() {
canceled = true;
statMessage = null;
}
/**
* Called from ProgressBarDemo to find out if the task has completed.
*/
public boolean isDone() {
return done;
}
/**
* Returns the most recent status message, or null if there is no current status
* message.
*/
public String getMessage() {
return statMessage;
}
/**
* The actual long running task. This runs in a SwingWorker thread.
*/
class ActualTask {
ActualTask() {
// Fake a long task,
// making a random amount of progress every second.
while (!canceled && !done) {
try {
Thread.sleep(1000); // sleep for a second
current += Math.random() * 100; // make some progress
if (current >= lengthOfTask) {
done = true;
current = lengthOfTask;
}
statMessage = "Completed " + current + " out of " + lengthOfTask + ".";
} catch (InterruptedException e) {
System.out.println("ActualTask interrupted");
}
}
}
}
}
/**
* This is the 3rd version of SwingWorker (also known as SwingWorker 3), an
* abstract class that you subclass to perform GUI-related work in a dedicated
* thread. For instructions on and examples of using this class, see:
*
* http://java.sun.com/docs/books/tutorial/uiswing/misc/threads.html
*
* Note that the API changed slightly in the 3rd version: You must now invoke
* start() on the SwingWorker after creating it.
*/
abstract class SwingWorker {
private Object value; // see getValue(), setValue()
/**
* Class to maintain reference to current worker thread under separate
* synchronization control.
*/
private static class ThreadVar {
private Thread thread;
ThreadVar(Thread t) {
thread = t;
}
synchronized Thread get() {
return thread;
}
synchronized void clear() {
thread = null;
}
}
private ThreadVar threadVar;
/**
* Get the value produced by the worker thread, or null if it hasn't been
* constructed yet.
*/
protected synchronized Object getValue() {
return value;
}
/**
* Set the value produced by worker thread
*/
private synchronized void setValue(Object x) {
value = x;
}
/**
* Compute the value to be returned by the <code>get</code> method.
*/
public abstract Object construct();
/**
* Called on the event dispatching thread (not on the worker thread) after the
* <code>construct</code> method has returned.
*/
public void finished() {
}
/**
* A new method that interrupts the worker thread. Call this method to force the
* worker to stop what it's doing.
*/
public void interrupt() {
Thread t = threadVar.get();
if (t != null) {
t.interrupt();
}
threadVar.clear();
}
/**
* Return the value created by the <code>construct</code> method. Returns null
* if either the constructing thread or the current thread was interrupted
* before a value was produced.
*
* @return the value created by the <code>construct</code> method
*/
public Object get() {
while (true) {
Thread t = threadVar.get();
if (t == null) {
return getValue();
}
try {
t.join();
} catch (InterruptedException e) {
Thread.currentThread().interrupt(); // propagate
return null;
}
}
}
/**
* Start a thread that will call the <code>construct</code> method and then
* exit.
*/
public SwingWorker() {
final Runnable doFinished = new Runnable() {
public void run() {
finished();
}
};
Runnable doConstruct = new Runnable() {
public void run() {
try {
setValue(construct());
} finally {
threadVar.clear();
}
SwingUtilities.invokeLater(doFinished);
}
};
Thread t = new Thread(doConstruct);
threadVar = new ThreadVar(t);
}
/**
* Start the worker thread.
*/
public void start() {
Thread t = threadVar.get();
if (t != null) {
t.start();
}
}
}
|
cs |
훌 륭 하 다 ...
'개발 실무' 카테고리의 다른 글
| [JAVA][SWING]ActionListener 사용설명서 (0) | 2018.09.12 |
|---|---|
| [JAVA][eclipse][ERROR] eclipse PHOTON 설치 오류 (1) | 2018.09.11 |
| [JAVA][SWING] 팝업 JOptionPane (showInputDialog, showConfirmDialog, showMessageDialog) (0) | 2018.09.11 |
| [JAVA][SWING] 메뉴(JMenuBar, JMenu, JMenuItem, MenuActionListener) (0) | 2018.09.11 |
| [JAVA][SWING] Drag-and-drop 파일선택시 드레그 앤 드롭 구현 (1) | 2018.09.10 |