Question

Context

The following code produces a "nice" looking "Hello World"

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

Now, if instead, I draw each character string, and manually advance by fontMetrics.getCharWidth(c) then I end up with a narrow/crowded looking "Hello World".

Questions

Why does this happen? What else do I need to add to, besides each character's "advance", to ensure that the characters are well spaced?

Was it helpful?

Solution

which method in Graphics do you use to render char ? here is the code that I wrote and it runs perfectly and results of both rendering methods are exactly the same, would you please share that 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) ;
    }
}

}

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top