Changing Font Style when Clicking on a JButton Java
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.
Comments
-
Sobiaholic over 3 years
How to change the
STYLE
of theFont
when clicking on aJButton
?I'm trying to have 3 buttons each change styles to
PLAIN
orBOLD
orITALIC
I've read the
font Class API
but I there is nothing likesetStyle
we can onlygetStyle
I find font class in java is quite complicated more than it should :S.
-
Sobiaholic over 12 yearsawesome! so we have to
setFont
each time we want to edit any parameter. I tried to use thederiveFont
before but I did not know how to use it. Now it's completely clear :) Thanks @Hovercraft ! -
Sobiaholic over 12 yearsThanks :) I read it already before posting but it was unclear. thanks to @Hovercraft his example helped me a lot!
-
Sobiaholic over 12 yearsI got a question, how about if I want the text to be
ITALIC
andBOLD
?