H G
H G

Reputation: 11

Java Applet: How do I draw a string in a square shape?

How would I go about drawing a string/character array so that it is written in a square shape with equal spacing between the characters? The larger the array, bigger the square. Is there a way to divide the numbers of characters by the length and get certain coordinates in the rectangle?

I thought about going through the array and getting the entire length of strings using a for loop. Then making that the length of my square edge. But I can't envision how to.

Upvotes: 1

Views: 583

Answers (1)

Tilo
Tilo

Reputation: 3335

Use getFontMetrics() to find out how much space the string will take up, and then draw character by character, adding the required extra space. Here is the code:

import java.awt.*;

// ...

@Override
public void paint(Graphics g) {
    String testString = "The quick brown fox jumps.";
    Rectangle testRectangle = new Rectangle(10, 50, 200, 20);

    Graphics2D g2d = (Graphics2D)g;
    g2d.setColor(Color.BLACK);
    g2d.draw(testRectangle);

    FontMetrics fm = g2d.getFontMetrics();
    int stringWidth = fm.stringWidth(testString);
    int extraSpace  = (testRectangle.width - stringWidth) / (testString.length() - 1);
    int x = testRectangle.x;
    int y = testRectangle.y + fm.getAscent();
    for (int index = 0; index < testString.length(); index++) {
        char c = testString.charAt(index);
        g2d.drawString(String.valueOf(c), x, y);
        x += fm.charWidth(c) + extraSpace;
    }
}

And this is what it looks like:

enter image description here

In order to get more accurate results Graphics2D also allows you to calculate with float instead of int.

Upvotes: 2

Related Questions