Naturally, Java allows you to use a variety of font families, such as Roman and Helvetica. Java also allows you to use any of three font styles: plain, bold, and italic. And Java allows you to use a variety of font sizes, specified in points.
To control the font, style, and size, you create instances of the
Font
class; you then use the setFont
method to
associate those instances with the graphics context.
For example, the following version of the print
method writes a
string using a 12-point Helvetica bold font:
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) {
g.setFont(new Font("Helvetica", Font.BOLD, 12));
g.drawString(title, 100, 50);
}
}
If you want a plain font, substitute PLAIN
for BOLD
. If you
want an italic font, substitute ITALIC
for BOLD
.