View Javadoc

1   package junit.awtui;
2   
3   import java.awt.*;
4   
5   public class ProgressBar extends Canvas {
6   	public boolean fError= false;
7   	public int fTotal= 0;
8   	public int fProgress= 0;
9   	public int fProgressX= 0;
10  
11  	public ProgressBar() {
12  		super();
13  		setSize(20, 30);
14  	}
15  	
16  	private Color getStatusColor() {
17  		if (fError)
18  			return Color.red;
19  		return Color.green;
20  	}
21  	
22  	public void paint(Graphics g) {
23  		paintBackground(g);
24  		paintStatus(g);
25  	}
26  	
27  	public void paintBackground(Graphics g) {
28  		g.setColor(SystemColor.control);
29  		Rectangle r= getBounds();
30  		g.fillRect(0, 0, r.width, r.height);
31  		g.setColor(Color.darkGray);
32  		g.drawLine(0, 0, r.width-1, 0);
33  		g.drawLine(0, 0, 0, r.height-1);
34  		g.setColor(Color.white);
35  		g.drawLine(r.width-1, 0, r.width-1, r.height-1);
36  		g.drawLine(0, r.height-1, r.width-1, r.height-1);
37  	}
38  	
39  	public void paintStatus(Graphics g) {
40  		g.setColor(getStatusColor());
41  		Rectangle r= new Rectangle(0, 0, fProgressX, getBounds().height);
42  		g.fillRect(1, 1, r.width-1, r.height-2);
43  	}
44  	
45  	private void paintStep(int startX, int endX) {
46  		repaint(startX, 1, endX-startX, getBounds().height-2);
47  	}
48  	
49  	public void reset() {
50  		fProgressX= 1;
51  		fProgress= 0;
52  		fError= false;
53  		paint(getGraphics());
54  	}
55  	
56  	public int scale(int value) {
57  		if (fTotal > 0)
58  			return Math.max(1, value*(getBounds().width-1)/fTotal);
59  		return value; 
60  	}
61  	
62  	public void setBounds(int x, int y, int w, int h) {
63  		super.setBounds(x, y, w, h);
64  		fProgressX= scale(fProgress);
65  	}
66  	
67  	public void start(int total) {
68  		fTotal= total;
69  		reset();
70  	}
71  	
72  	public void step(boolean successful) {
73  		fProgress++;
74  		int x= fProgressX;
75  
76  		fProgressX= scale(fProgress);
77  
78  		if (!fError && !successful) {
79  			fError= true;
80  			x= 1;
81  		}
82  		paintStep(x, fProgressX);
83  	}
84  }