Changing Font Style when Clicking on a JButton Java

21,783

Solution 1

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.

Solution 2

you can do it as follow

JButton myButton=new JButton();
myButton.setText("My Button");
myButton.setFont(new Font("Serif", Font.BOLD, 14));

Solution 3

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.

Solution 4

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

Share:
21,783
Sobiaholic
Author by

Sobiaholic

I do code and talks @ IBM.

Updated on November 17, 2020

Comments

  • Sobiaholic
    Sobiaholic over 3 years

    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.

  • Sobiaholic
    Sobiaholic over 12 years
    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
    Sobiaholic over 12 years
    Thanks :) I read it already before posting but it was unclear. thanks to @Hovercraft his example helped me a lot!
  • Sobiaholic
    Sobiaholic over 12 years
    I got a question, how about if I want the text to be ITALIC and BOLD ?