Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Changing Font Style when Clicking on a JButton Java

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.

like image 257
Sobiaholic Avatar asked Dec 30 '11 11:12

Sobiaholic


2 Answers

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.

like image 145
Hovercraft Full Of Eels Avatar answered Sep 27 '22 18:09

Hovercraft Full Of Eels


you can do it as follow

JButton myButton=new JButton();
myButton.setText("My Button");
myButton.setFont(new Font("Serif", Font.BOLD, 14));
like image 41
Hemant Metalia Avatar answered Sep 27 '22 16:09

Hemant Metalia