7

How to change the STYLE of the Font when clicking on a JButton ?

I'm trying to have 3 buttons each change styles to PLAIN or BOLD or ITALIC

I've read the font Class API but I there is nothing like setStyle we can only getStyle

I find font class in java is quite complicated more than it should :S.

mKorbel
  • 109,525
  • 20
  • 134
  • 319
Sobiaholic
  • 2,927
  • 9
  • 37
  • 54
  • 2
    See also http://stackoverflow.com/questions/8675038/increasing-decreasing-font-size-inside-textarea-using-jbutton for a very similar question – Robin Dec 30 '11 at 11:51

4 Answers4

14

You would need to call setFont(...) not setStyle.

For example, if you want to keep the same font but change the style of a JTextField called "field" you could do something like:

field.setFont(field.getFont().deriveFont(Font.BOLD));

Edit
To set the font to both bold and italic, you'd or the bitmaps:

field.setFont(field.getFont().deriveFont(Font.BOLD | Font.ITALIC));

Please note that this uses the bitwise inclusive OR operator which uses a single pipe symbol: | rather than the logical OR operator which uses a double pipe symbol: ||.

Also note for further subtlety and confusion that | can be used as a logical OR operator, but you'll usually prefer to use || for this since the latter is a "short-circuit" operator in that if the left hand side of the expression is true, the right hand side isn't even evaluated.

Hovercraft Full Of Eels
  • 283,665
  • 25
  • 256
  • 373
  • awesome! so we have to `setFont` each time we want to edit any parameter. I tried to use the `deriveFont` before but I did not know how to use it. Now it's completely clear :) Thanks @Hovercraft ! – Sobiaholic Dec 30 '11 at 13:31
  • I got a question, how about if I want the text to be `ITALIC` and `BOLD` ? – Sobiaholic Dec 30 '11 at 13:40
5

you can do it as follow

JButton myButton=new JButton();
myButton.setText("My Button");
myButton.setFont(new Font("Serif", Font.BOLD, 14));
Hemant Metalia
  • 29,730
  • 18
  • 72
  • 91
4

Get the current Font, use deriveFont to get a new Font similar to the current one but with a new style, and apply the new font.

JB Nizet
  • 678,734
  • 91
  • 1,224
  • 1,255
  • Thanks :) I read it already before posting but it was unclear. thanks to @Hovercraft his example helped me a lot! – Sobiaholic Dec 30 '11 at 13:35
2

As an alternative, you might look at the StyledEditorKit actions available to JEditorPane. There's a related example here and a tutorial here.

Community
  • 1
  • 1
trashgod
  • 203,806
  • 29
  • 246
  • 1,045