Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to Change Font Size in drawString Java

How to make the font size bigger in g.drawString("Hello World",10,10); ?

like image 912
zbz.lvlv Avatar asked Aug 15 '13 09:08

zbz.lvlv


People also ask

How do you change the font size on a drawstring?

How do I change the font size of a g or g2d drawstring object? First create your g (or g2d) drawstring object String string = "Hello World"; then create a Font object Font stringFont = new Font( "SansSerif", Font. PLAIN, 18 ); Next set the Font object to the g or g2d object g2d.

How do I increase the font size of a String in Java?

You can't actually change the size of an existing Font object. The best way to achieve a similar effect is to use the deriveFont(size) method to create a new almost identical Font that is a different size. Note: you need to specify that bigNumber is a float, otherwise you'll trigger the deriveFont(int style) overload.


2 Answers

g.setFont(new Font("TimesRoman", Font.PLAIN, fontSize));  

Where fontSize is a int. The API for drawString states that the x and y parameters are coordinates, and have nothing to do with the size of the text.

like image 96
John Snow Avatar answered Sep 21 '22 01:09

John Snow


Because you can't count on a particular font being available, a good approach is to derive a new font from the current font. This gives you the same family, weight, etc. just larger...

Font currentFont = g.getFont();
Font newFont = currentFont.deriveFont(currentFont.getSize() * 1.4F);
g.setFont(newFont);

You can also use TextAttribute.

Map<TextAttribute, Object> attributes = new HashMap<>();

attributes.put(TextAttribute.FAMILY, currentFont.getFamily());
attributes.put(TextAttribute.WEIGHT, TextAttribute.WEIGHT_SEMIBOLD);
attributes.put(TextAttribute.SIZE, (int) (currentFont.getSize() * 1.4));
myFont = Font.getFont(attributes);

g.setFont(myFont);

The TextAttribute method often gives one even greater flexibility. For example, you can set the weight to semi-bold, as in the example above.

One last suggestion... Because the resolution of monitors can be different and continues to increase with technology, avoid adding a specific amount (such as getSize()+2 or getSize()+4) and consider multiplying instead. This way, your new font is consistently proportional to the "current" font (getSize() * 1.4), and you won't be editing your code when you get one of those nice 4K monitors.

like image 20
daveca Avatar answered Sep 19 '22 01:09

daveca