Search code examples
javadrawdrawstring

How can I separate the letter in string when drawing


I want to draw a string that I take from a jtextarea, but I want to draw with 20px space to each letter, but I think I can't do this with drawstring and I can't draw a char per time with drawchars, so what can I do?

I want to write a letter above each trace, but how I'm doing know is not working

public void paintComponent(Graphics g)
{
    super.paintComponent(g);
    for(int i=0;i<PalavraAdivinha.length();i++)
    {
        g.fillRect(InicioTraco+(i*40), 240, 40, 5);
    }
    Font titulo = new Font("Arial",Font.BOLD,40);
    g.setFont(titulo);
    g.drawString("Adivinhe a palavra", 0,100 );
    if(PalavraDigitada != null)
    {
        g.drawString(PalavraDigitada, InicioTraco, 235);
    }
}

Solution

  • You can draw each character seperately. By retrieving the FontMetrics currently used by the Graphics object, you can measure the width of each character, so you can advance using this width and a given seperation.

    public static void drawString(Graphics g, String string, int x, int y,
            int seperation) {
    
        FontMetrics metrics = g.getFontMetrics();
        int drawx = x;
    
        for (int i = 0; i < string.length(); ++i) {
            String character = "" + string.charAt(i);
    
            g.drawString(character, drawx, y);
            drawx += seperation + metrics.stringWidth(character);
        }
    }
    

    Example Code

    public static void main(String[] args) throws IOException {
        BufferedImage image = new BufferedImage(512, 256,
                BufferedImage.TYPE_INT_ARGB);
        Graphics g = image.getGraphics();
        g.setColor(Color.BLACK);
        for (int i = 0; i < 10; ++i)
            drawString(g, "i am drawn with seperation " + i, 24, 24 + 16 * i, i);
        ImageIO.write(image, "png", new File("output.png"));
    }
    

    Result

    Several strings with increasing amounts of seperation