Search code examples
javatextgraphicsposition

Does anyone know an approximate text to pixel ratio? (Java String positioning)


Like you see in almost all text-editing softwares, css and more, I want to position my Text with java.awt. My test code for this is:

public class Test {
    public static void main(String[] args) {
        // creating the frame
        JFrame frame = new JFrame("Test");
        frame.setSize(1000, 800);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setLocationRelativeTo(null);

        // variables
        int x1 = 50;
        int x2 = 500;
        int y1 = 70;
        int y2 = 150;
        int y3 = 230;
        int width = 400;
        int height = 60;
        int fontsize = 40;
        String text = "This is a test";

        frame.add(new JPanel() {
            public void paint(Graphics g) {
                g.setColor(Color.BLACK);

                // borders
                g.drawRect(x1, y1, width, height); // top
                g.drawRect(x1, y2, width, height); // middle
                g.drawRect(x1, y3, width, height); // bottom
                g.drawRect(x2, y1, width, height); // left
                g.drawRect(x2, y2, width, height); // center
                g.drawRect(x2, y3, width, height); // right

                g.setFont(new Font("arial", Font.PLAIN, fontsize));

                // top
                g.drawString(text, x1 + 10, y1 + fontsize); // x1 + 10 (10 is a buffer)
                // center
                g.drawString(text, x1 + 10, y2 + fontsize + (height - fontsize) / 2);
                // bottom
                g.drawString(text, x1 + 10, y3 + height);

                // left
                g.drawString(text, x2, y1 + fontsize);
                // middle
                g.drawString(text, x2 + width / 2 - text.length() * (fontsize/5), y2 + fontsize + (height - fontsize) / 2);
                // right
                g.drawString(text, x2 + (width - text.length() * (fontsize/5)), y3 + height);

            }
        });
        frame.setVisible(true);
    }
}

Of course it kind of looks messy, but I'm working on it in an API project where I'm implementing ux features atm.


Solution

  • You can use the FontMetrics object of the Graphics object to get information about the Font metrics to help with determining the size of the text:

    FontMetrics fm = g.getFontMetrics();
    

    See: Measuring Text tutorial.

    Why are you doing custom painting? Why are you not using Swing components with layout managers to manage the UI? We can't give specific advice since we don't know what the goal of your posted code is.