1 package com.sshtools.ui.awt; 2 3 import java.awt.Canvas ; 4 import java.awt.Color ; 5 import java.awt.Dimension ; 6 import java.awt.FontMetrics ; 7 import java.awt.Graphics ; 8 import java.awt.Rectangle ; 9 10 public class ProgressBar extends Canvas { 11 12 public ProgressBar(int min, int max, int val) { 13 this.min = min; 14 this.max = max; 15 this.val = val; 16 } 17 18 public Dimension getPreferredSize() { 19 return new Dimension (100, 16); 20 } 21 22 public Dimension getMinimumSize() { 23 return new Dimension (super.getMinimumSize().width, 16); 24 } 25 26 public int getMax() { 27 return max; 28 } 29 30 public void setMax(int max) { 31 this.max = max; 32 repaint(); 33 } 34 35 public int getMin() { 36 return min; 37 } 38 39 public void setMin(int min) { 40 this.min = min; 41 repaint(); 42 } 43 44 public int getVal() { 45 return val; 46 } 47 48 public void setVal(int val) { 49 this.val = val; 50 paintAll(getGraphics()); 51 } 52 53 public Color getProgressColor() { 54 return progressColor; 55 } 56 57 public void setProgressColor(Color progressColor) { 58 this.progressColor = progressColor; 59 repaint(); 60 } 61 62 public String getProgressString() { 63 return progressString; 64 } 65 66 public void setProgressString(String progressString) { 67 this.progressString = progressString; 68 repaint(); 69 } 70 71 public void paint(Graphics g) { 72 super.paint(g); 73 Rectangle bounds = getBounds(); 74 g.setColor(getForeground()); 75 g.drawRect(0, 0, bounds.width, bounds.height); 76 g.setColor(progressColor != null ? progressColor : Color.blue); 77 float scale = (float) val / ((float) max - (float) min); 78 g.fillRect(1, 1, (int) ((float) (bounds.width - 2) * scale), 79 bounds.height - 2); 80 String s = progressString != null ? progressString : (int) (scale * 100F) 81 + "%"; FontMetrics fm = getFontMetrics(getFont()); 83 int swidth = fm.stringWidth(s); 84 g.setColor(getForeground()); 85 g.drawString(s, (bounds.width - swidth) / 2, bounds.height / 2 86 + ( fm.getMaxAscent() / 2)); 87 } 88 89 private int min; 90 private int max; 91 private int val; 92 private Color progressColor; 93 private String progressString; 94 } | Popular Tags |