![]() |
![]() |
![]() |
![]() |
![]() |
|
Now it is time to
combine the definition for
the Meter class provided in Segment 734 with the definition
provided in Segment 746. The text is drawn
on a baseline placed far enough under the lines to allow for the text and a
reasonable separation from the lines:
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 Dimension instance:
Dimension d = getSize();
int meterWidth = d.width * 3 / 4;
int meterHeight = meterWidth / 20;
int pointerPosition
= meterWidth * (value - minValue) / (maxValue - minValue);
int lineXOffset = (d.width - meterWidth) / 2;
int lineYOffset = d.height / 2;
g.drawLine(lineXOffset, lineYOffset,
lineXOffset + meterWidth, lineYOffset);
g.drawLine(lineXOffset + pointerPosition, lineYOffset,
lineXOffset + pointerPosition, lineYOffset - meterHeight);
// Prepare font
int fontSize = d.width / 30;
g.setFont(new Font("Helvetica", Font.BOLD, fontSize));
// Write title:
FontMetrics f = g.getFontMetrics();
int stringWidth = f.stringWidth(title);
int textXOffset = (d.width - stringWidth) / 2;
int 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);}
}