Java Font Advance, Char Width

Context

The following code creates a โ€œbeautifulโ€ look "Hello World"

graphics.drawString("Hello World", 30, 30);

Now, if instead I draw each line of characters and manually advance to fontMetrics.getCharWidth(c), then I get a narrow / crowded look "Hello World".

Questions

Why is this happening? What else do I need to add, except for each forward character, to make sure the characters are well spaced?

+3
source share
1 answer

which method in Graphics do you use to render char? here is the code i wrote and it works great and the results of both rendering methods are exactly the same, could you share this part of your code?

public class Test1 extends JPanel{

public static void main(String[] args) {

    Test1 test = new Test1() ;

    JFrame frame = new JFrame() ;
    frame.add(test) ;
    frame.setSize(800 , 600) ;
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE) ;
    frame.setVisible(true) ;

}


@Override
public void paint(Graphics g) {     
    String text = "This is a text , Hello World!" ;

    g.drawString(text, 0, 100) ;        
    drawString(text, g, 0, 120) ;       
}

private void drawString (String s , Graphics g , int x , int y){
    for (int c1=0 ; c1 < s.length() ; c1++){

        char ch = s.charAt(c1); 
        g.drawString(ch+"", x, y) ;
        x+= g.getFontMetrics().charWidth(ch) ;
    }
}

}

+1
source

All Articles