Getting string size in java (without having a Graphics object available)

前端 未结 6 581
南方客
南方客 2021-01-11 12:37

I\'m trying to write application which need to draw many strings using Graphics2D class in Java. I need to get sizes of each String object (to calculate exact p

6条回答
  •  迷失自我
    2021-01-11 13:27

    Try with the FontMetrics class; the stringWidth method returns the size of a string. An example:

    JComponent c = getSomeKindOfJComponent();
    FontMetrics fm = c.getFontMetrics(c.getFont()); // or another font
    int strw = fm.stringWidth("My text");
    

提交回复
热议问题