Grinding Java - Searching the WWW in Java:grinding5.java
Appearance
import java.awt.*; /** * a class to show a percentage bar with the correct percentage painted in * one color and the number of percent on top. **/ public class ProgressBar extends Panel { /** * this constructor accepts the following parameters: * backColor - the color of the border of the window * frontColor - the color of the bar. * textColor - the color in which the percentage figure will be painted. **/ public ProgressBar(Color backColor, Color frontColor, Color textColor) { backColor = this.backColor; frontColor = this.frontColor; textColor = this.textColor; percent = 0; } /** * this constructor accepts the following parameters: * backColor - the color of the border of the window * frontColor - the color of the bar. * textColor - the color in which the percentage figure will be painted. * textFont - the font to use in writing the percentage. **/ public ProgressBar(Color backColor, Color frontColor, Color textColor, Font textFont) { backColor = this.backColor; frontColor = this.frontColor; textColor = this.textColor; setFont(textFont); percent = 0; } /** * this method draws the progress bar with the correct percentage filled in. **/ public void paint (Graphics g) { int width = getSize().width; int height = getSize().height; g.setColor(backColor); g.drawRect(0,0,width-1,height-1); g.setColor(frontColor); g.fillRect(1,1,(int)((width-2) * ((double)percent) / 100),height-2); String percentage = Integer.toString(percent) + "%"; Font textFont = g.getFont(); FontMetrics fntMetric = g.getFontMetrics(textFont); int x = (width / 2) - (fntMetric.stringWidth(percentage) / 2); int y = (height / 2) - (fntMetric.getHeight() / 2); g.setColor(textColor); g.drawString(percentage,x,y); } /** * set the size of the progress bar to a new size. **/ void setPercentage(int percent) { this.percent = percent; repaint(); } private int percent; private Color backColor; private Color frontColor; private Color textColor; }