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