开发者

Positioning string in graphic + java

开发者 https://www.devze.com 2023-02-18 14:00 出处:网络
I am trying to write an integer number inside the graphic figure and want it positioning to always be at the center.

I am trying to write an integer number inside the graphic figure and want it positioning to always be at the center.

Is there any way to do so?

Currently I am writing this which is not good :

Font font = new Font("Arial", Font.BOLD, 20);

g.setFont(font);
g.setColor(this.color);
g.fillOval(b.x, b.y, b.width, b.height);
g.setCol开发者_开发技巧or(Color.black);
g.drawString("1", b.x + b.width/2 , b.y+ b.height/2);

where b is a rectangle.


You can use the FontMetrics class to determine the exact size of the String you want to display, and then subtract half its X and Y dimensions from your center point, and draw it there, like this:

    FontMetrics fm = g.getFontMetrics();
    Rectangle2D rect = fm.getStringBounds("1", g);
    g.drawString("1", (int) (b.x + b.width/2 - rect.getWidth()/2),
                      (int) (b.y + b.height/2 + rect.getHeight()/2));


I think the above answer should be satisfactory though not precise. I am not sure why but that is how it goes. That is how I would for example center any object/component on a panel. But with strings it is not that easy. Probably it has something to do with ascent descent of a text, that is what I got from some code I found on the net a long while ago.

For the code see below. It shows a very simple example presenting how it works versus the above solution, you just need to comment/un-comment appropriate code, run program once for each variation and compare/see.

I must admit I am not the author of the algorithm (sadly I do not remember his/hers name - thank you for the code & good job), though I have implemented the methods allowing for an additional offset for x and y.

import java.awt.Color;
import java.awt.FontMetrics;
import java.awt.Graphics;
import java.awt.HeadlessException;
import java.awt.geom.Rectangle2D;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;

public final class StringPainter
{
    private StringPainter()
    {
    }

    public static void drawCenteredString(String s, int w, int h, Graphics g)
    {
        drawCenteredString(s, 0, 0, w, h, g);
    }

    public static void drawCenteredString(String s, int offsetX, int offsetY, int w, int h, Graphics g)
    {
        FontMetrics fm = g.getFontMetrics();
        int x = (w - fm.stringWidth(s)) / 2 + offsetX;
        int y = (fm.getAscent() + (h - (fm.getAscent() + fm.getDescent())) / 2) + offsetY;
        g.drawString(s, x, y);
    }

    public static void main(String[] args)
    {
        SwingUtilities.invokeLater(new Runnable()
        {
            @Override
            public void run()
            {
                createGUI();
            }
        });
    }

    private static void createGUI() throws HeadlessException
    {
        JPanel p = new JPanel()
        {
            private static final long serialVersionUID = 1L;

            @Override
            protected void paintComponent(Graphics g)
            {
                super.paintComponent(g);
                String str = "TEST";
//              StringPainter.drawCenteredString(str, 0, 0, getWidth(), getHeight(), g);
                FontMetrics fm = g.getFontMetrics();
                Rectangle2D rect = fm.getStringBounds(str, g);
                g.drawString(str, (int) (getX() + getWidth() / 2 - rect.getWidth() / 2),
                        (int) (getY() + getHeight() / 2 + rect.getHeight() / 2));
                g.setColor(Color.GREEN);
                g.fillOval(getWidth() / 2 - 2, getHeight() / 2 - 2, 4, 4);
            }
        };
        JFrame f = new JFrame();
        f.setContentPane(p);
        f.setSize(800, 600);
        f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        f.setVisible(true);
    }
}

Hope it helps.

Enjoy Java, Boro.

0

精彩评论

暂无评论...
验证码 换一张
取 消