![]() |
![]() |
![]() |
![]() |
![]() |
|
The following produces a rotated meter.
import java.awt.*;
import java.awt.geom.*;
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 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);
transform.rotate(- Math.PI / 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);}
}