Il 10.10.2015 18.01, Steve Richter ha scritto:
> I am hoping to use java.awt.font.TextMeasurer to measure the width of a text string
> rendered in a proportional font.
Non the right way, I suppose.
> But java code that uses the java.awt.font class does not compile for me. Package does not exist.
>
> I have never compiled java code before. Is there a CLASSPATH or other environment variable that must be set to use Java.awt ?
>
> If not awt is there another graphics package I can use?
>
> here is my code. To compile I set the CLASSPATH = ".". Copy the code to an IFS stream file as ascii. Then run javac from QSH.
Nothing todo with classpath. It were just typing mistakes.
>
>
> import java.lang.*;
> import java.awt.*;
> // get package not found error on this code.
> Java.awt.Font f = new Java.awt.Font("Helvetica",
> Java.awt.Font.Bold, 24 ) ;
Here it is, case matters! Java.awt needs to be lowercase, as you put in
imports. Then, if you import java.awt.* you may use just "Font f".
Further more, Font.Bold doesn't exists, you should use Font.BOLD instead.
To measure the width of a text string, you need also a graphics
environment, non just a font. The font itself doesn't carry any
information about graphics, it needs a renderer. For example the
graphics environment of a printer may be not the same as the graphics
environment of a display.
You can use:
FontMetrics fm = Toolkit.getDefaultToolkit().getFontMetrics(font);
int width = fm.stringWidth(text);
or better
graphics.getFontMetrics()
int width = fm.stringWidth(text);
where you can get graphics from any awt container or component or a
printer aswell.
In both cases width is expressed in pixels.
Toolkit.getDefaultToolkit() will return the toolkit for the current
display, thus your width will be calculated for the current primary
screen, that can be different from the secondary one, or any other device.