Changing Font Style when Clicking on a JButton Java

▼魔方 西西 提交于 2019-12-18 16:36:25

问题


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.


回答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.




回答2:


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.




回答3:


you can do it as follow

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



回答4:


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



来源:https://stackoverflow.com/questions/8679088/changing-font-style-when-clicking-on-a-jbutton-java

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!