Home Segments Top Top Previous Next

737: Mainline

Whenever you make a change to the value of a graphics-context variable, you should first obtain the current value, and you should restore that value later. For example, you can use the getColor method to obtain the current Color instance associated with the graphics context. Then, you can change to another Color instance temporarily. Finally, you can use the setColor method again, this time to restore the graphics context to the original state:

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();}
 public int getValueAtCoordinates (int x, int y) {
  Dimension d = getSize();
  int meterWidth = d.width * 3 / 4;
  int xOffset = (d.width - meterWidth) / 2;
  float fraction = (float)(x - xOffset) / meterWidth;
  return (int)Math.round(fraction * (maxValue - minValue) + minValue);
 }
 public void paint(Graphics g) {
  // Obtain current Color instance:
  Color colorHandle = g.getColor();                             
  // Reset color temporarily:
  g.setColor(Color.blue);                                       
  // 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);
  // Restore color:
  g.setColor(colorHandle);                                      
 } 
 public Dimension getMinimumSize() {return new Dimension(150, 150);}  
 public Dimension getPreferredSize() {return new Dimension(150, 150);}      
}