Home Segments Top Top Previous Next

1121: Mainline

Doing path-oriented drawing requires including the java.awt.geom package, as shown in the following adaptation of the Meter definition given in Segment 1113. Note also that moveTo and lineTo require float arguments, rather than int arguments. Also, the Graphics2D class defines a drawString method that takes float arguments, so the following definition uses float variables for drawing the text. Thus, both line drawing and text drawing are done in user coordinates.

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);
  float lineXOffset = (d.width - meterWidth) / 2;
  float lineYOffset = d.height / 2;
  GeneralPath path = new GeneralPath();                         
  path.moveTo(lineXOffset, lineYOffset);                        
  path.lineTo(lineXOffset + meterWidth, lineYOffset);           
  path.moveTo(lineXOffset + pointerPosition, lineYOffset);      
  path.lineTo(lineXOffset + pointerPosition,                    
              lineYOffset - meterHeight);                       
  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 = (d.width - stringWidth) / 2;  
  float textYOffset = (d.height / 2) + (2 * f.getHeight());  
  g.drawString(title, textXOffset, textYOffset);  
 } 
 public Dimension getMinimumSize() {return new Dimension(150, 100);}  
 public Dimension getPreferredSize() {return new Dimension(150, 100);}  
}