10

I have a drawString() method in my paintComponent method. Is there a way to make the text drawn by the drawString() bold? Also, is there a way to make the text bigger? I would like to avoid using JLabels, unless it is absolutely necessary.

Jack
  • 131,802
  • 30
  • 241
  • 343
reesjones
  • 704
  • 3
  • 9
  • 28

3 Answers3

20

According to documentation of drawString:

Draws the text given by the specified string, using this graphics context's current font and color. The baseline of the leftmost character is at position (x, y) in this graphics context's coordinate system

Indeed, Graphics class has the setFont(Font font) method available:

g.setFont(new Font("default", Font.BOLD, 16));
Jack
  • 131,802
  • 30
  • 241
  • 343
  • 7
    You could use g.getFont().deriveFont(Font.BOLD) if all you wanted to do was change the font style of the current font... – MadProgrammer Feb 10 '13 at 19:53
  • @MadProgrammer Excellent, this is what I am looking for. You should have written your answer here. Will +1 without hesitation. – user3437460 Jun 30 '15 at 18:54
  • In case this is not clear to others, `g` is the canvas. If, for example, you're overriding `public void paintComponent(Graphics canvas)`, then you'll want `canvas.setFont(new Font("default", Font.BOLD, 16));`. – Mark Cramer Jun 05 '16 at 23:03
1

You have to set the font before drawing the text.

g.setFont(font);
Dan D.
  • 32,246
  • 5
  • 63
  • 79
1

There are methods: setFont(Font) - Method in class java.awt.Component Sets the font of this component. setFont(Font) - Method in class java.awt.Container Sets the font of this container. setFont(Font) - Method in class java.awt.Graphics Sets this graphics context's font to the specified font.

Dumas45
  • 501
  • 1
  • 10
  • 20