tags:

views:

250

answers:

2

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!

+2  A: 

What about using FontMetrics? You can obtain it from Graphics object with g.getFontMetrics().

Than you can retrieve max descent or ascent or directly height (using getHeight), so your implementation will be font-indipendent and it should work fine.. check documentation here!

EDIT (to explain comments): there is no a direct way to tell to a string to draw itself in a manner that can fit a box. You have to do it by yourself.. like start from a max font size and check if width fits the box, otherwise decrement size and try again. For height you should FIRST decide (or obtain) max font height, then you can set how many pixel should the box be.

Jack
Yes, particularly FontMetrics.stringWidth(): http://java.sun.com/j2se/1.5.0/docs/api/java/awt/FontMetrics.html#stringWidth%28java.lang.String%29
Suppressingfire
Yes but what to do with those metrics? I tried drawing the string at y + fontmetrics.getAscent() and that also draws the text way too low.
Folkert van Heusden
Also other problem is that these methods tell you how large your text will become: isn't there a way that I can say this string s must fit in this boundingbox?
Folkert van Heusden
I don't think stringWidth is the case because we're talking about height. You should use **getHeight** that, how documentation states: "Gets the standard height of a line of text in this font. This is the distance between the baseline of adjacent lines of text. It is the sum of the leading + ascent + descent."You cannot bound a string, what should it do? resize it automatically?
Jack
A: 

I think I solved it somewhat:

boundingBoxHeight: height of box in which the text should fit yOffset where to start drawing the font

            Font f = new Font("Arial", Font.PLAIN, boundingBoxHeight);
            g.setFont(f);
            FontMetrics fm = g.getFontMetrics();
            double shrink = ((double)textHeight / (double)fm.getHeight());
            double newSize = (double)textHeight * shrink;
            double newAsc  = (double)fm.getAscent() * shrink;
            int yOffset = (int)newAsc - fm.getLeading();
            f = f.deriveFont((float)newSize);
            g.setFont(f);

            g.drawString(str, 10, 100 + yOffset);

There's quite a bit of whitespace above the text though.

Folkert van Heusden