Home Segments Top Top Previous Next

1126: Mainline

Incorporating a transformation into the definition of the Meter's paint method enables you to write simpler arithmetic expressions.

For example, in the following, you see expressions specialized to realizing the meter's shape and other expressions specialized to centering the meter in the component. With that separation, you can easily, for example, add short vertical lines at the end of the meter's horizontal line. The shape expressions presume a coordinate system centered at the midpoint of the meter's horizontal line:

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);                                    
  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);}  
}