Home Segments Top Top Previous Next

733: Mainline

Now, it is time for you to learn to produce more sophisticated drawings.

For example, you can obtain an instance of the Dimension class using the getSize method with a component as the target. The width and height instance variables of the Dimension instance provide the current width and height of the component.

With the width and height in hand, you can draw not just a horizontal line with a simple vertical line at the proper place to represent the value of the value instance variable. Instead, you can draw a combination that fills out the window; places the vertical line at the position indicated by the values of the minValue, maxValue, and value variables; scales the vertical line in proportion to the horizontal line; and stays centered, even as you move, or change the size of, the window:

import java.awt.*;
import javax.swing.*;
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();}
 // Getter to be defined
 public void paint(Graphics g) {
  // Obtain Dimension instance:
  Dimension d = getSize();                                      
  // Draw:
  int meterWidth = d.width * 3 / 4;                             
  int meterHeight = meterWidth / 20;                            
  int dialPosition                                              
   = meterWidth * (value - minValue) / (maxValue - minValue);   
  int xOffset = (d.width - meterWidth) / 2;                     
  int yOffset = d.height / 2;                                   
  g.drawLine(xOffset, yOffset, xOffset + meterWidth, yOffset);  
  g.drawLine(xOffset + dialPosition, yOffset,                   
             xOffset + dialPosition, yOffset - meterHeight);    
 } 
 public Dimension getMinimumSize() {return new Dimension(150, 150);}  
 public Dimension getPreferredSize() {return new Dimension(150, 150);}      
}