The following version of the paint
method
in Meter
illustrates the use of stroke and paint refinements:
import java.awt.*; import javax.swing.*; import java.awt.geom.*; public class Meter extends JComponent implements MeterInterface { String title = "Title to Be Supplied"; int minValue, maxValue, value; public Meter (int x, int y) { minValue = x; maxValue = y; value = (y + x) / 2; } public void setValue(int v) {value = v; repaint();} public void setTitle(String t) {title = t; repaint();} public void paint(Graphics x) { Graphics2D g = (Graphics2D) x; // Obtain Dimension instance: Dimension d = getSize(); // Draw: float meterWidth = d.width * 3 / 4; float meterHeight = meterWidth / 20; float pointerPosition = meterWidth * (value - minValue) / (maxValue - minValue); // Offset to new origin: pointerPosition = pointerPosition - (meterWidth / 2); GeneralPath path = new GeneralPath(); path.moveTo(- meterWidth / 2, - meterHeight); path.lineTo(- meterWidth / 2, 0); path.lineTo(meterWidth / 2, 0); path.lineTo(meterWidth / 2, - meterHeight); path.moveTo(pointerPosition, 0); path.lineTo(pointerPosition, - meterHeight); AffineTransform transform = new AffineTransform(); transform.translate(d.width / 2, d.height / 2); g.setTransform(transform); BasicStroke stroke = new BasicStroke(10, BasicStroke.CAP_BUTT, BasicStroke.JOIN_BEVEL); g.setStroke(stroke); GradientPaint paint = new GradientPaint(- meterWidth / 2, 0, Color.blue, + meterWidth / 2, 0, Color.red); g.setPaint(paint); g.draw(path); // Prepare font int fontSize = d.width / 30; g.setFont(new Font("Helvetica", Font.BOLD, fontSize)); // Write title: FontMetrics f = g.getFontMetrics(); float stringWidth = f.stringWidth(title); float textXOffset = - stringWidth / 2; float textYOffset = 2 * f.getHeight(); g.drawString(title, textXOffset, textYOffset); } public Dimension getMinimumSize() {return new Dimension(150, 100);} public Dimension getPreferredSize() {return new Dimension(150, 100);} }