I have an application that extends a Frame. Then, it ll display a few lines of text using:
Font f = new Font("Arial", Font.PLAIN, 10);
g.setFont(f);
g.drawString("Test|great Yes ^.", x, y + 10);
Now what happens is that the text doesn t fit in the box around. E.g. I m expecting the text to fit in [x,y]-[x+width, y+10] (don t care about the width) but it falls somewhat below the y+10 line. Now for most characters ( T , e , etc.) this fits but | and g don t! They go below the y+10-line. It seems you can t use: draw at y + characterHeight. But what does work?
To see what I mean, here s some sample code:
import java.awt.*;
public class test extends Frame
{
public test()
{
/* retrieve max window size */
GraphicsEnvironment ge = GraphicsEnvironment.getLocalGraphicsEnvironment();
GraphicsDevice[] gs = ge.getScreenDevices();
GraphicsConfiguration [] gc = gs[0].getConfigurations();
Rectangle r = gc[0].getBounds();
setSize(r.width, r.height);
setVisible(true);
}
public void paint(Graphics g)
{
final int windowWidth = getSize().width;
final int windowHeight = getSize().height;
g.setColor(Color.BLUE);
g.fillRect(0, 0, windowWidth, windowHeight);
g.setColor(Color.WHITE);
g.fillRect(0, 100, windowWidth, 110);
int textHeight = 100;
Font f = new Font("Arial", Font.PLAIN, textHeight);
g.setFont(f);
g.setColor(Color.BLACK);
g.drawString("Test|great Yes ^.", 10, 100 + textHeight);
}
public void guiLoop()
{
for(;;) { try { Thread.sleep(1000); } catch(Exception e) { } }
}
public static void main(String [] args)
{
new test().guiLoop();
}
}
I tried the following code as well:
public void paint(Graphics g)
{
final int windowWidth = getSize().width;
final int windowHeight = getSize().height;
g.setColor(Color.BLUE);
g.fillRect(0, 0, windowWidth, windowHeight);
g.setColor(Color.WHITE);
g.fillRect(0, 100, windowWidth, 110);
int textHeight = 100;
String str = "Test|great Yes ^.";
Font f = new Font("Arial", Font.PLAIN, textHeight);
Rectangle2D boundingRectangle = f.getStringBounds(str, 0, str.length(), new FontRenderContext(null, false, false));
f = f.deriveFont((float)(textHeight * (textHeight / boundingRectangle.getHeight())));
boundingRectangle = f.getStringBounds(str, 0, str.length(), new FontRenderContext(null, false, false));
g.drawString(str, 10, 100 + (int)boundingRectangle.getHeight());
g.setFont(f);
g.setColor(Color.BLACK);
g.drawString(str, 10, 100 + textHeight);
}
This is somewhat better: the text is smaller so it might fit, but there s still the problem that the y-position is incorrect.
All help is appreciated!