[英]Changing Font Style when Clicking on a JButton Java
How to change the STYLE
of the Font
when clicking on a JButton
? 如何在单击
JButton
时更改Font
的STYLE
?
I'm trying to have 3 buttons each change styles to PLAIN
or BOLD
or ITALIC
我试图让3个按钮各自改变
PLAIN
或BOLD
或ITALIC
样式
I've read the font Class API
but I there is nothing like setStyle
we can only getStyle
我已经阅读了
font Class API
但我没有像setStyle
那样只有getStyle
I find font class in java is quite complicated more than it should :S. 我发现java中的字体类比它应该更复杂:S。
You would need to call setFont(...)
not setStyle. 你需要调用
setFont(...)
而不是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”的JTextField的样式,则可以执行以下操作:
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: |
请注意,这使用按位包含OR运算符,该运算符使用单个管道符号:
|
rather than the logical OR operator which uses a double pipe symbol: ||
而不是使用双管道符号的逻辑OR运算符:
||
. 。
Also note for further subtlety and confusion that |
另请注意进一步微妙和混乱是
|
can be used as a logical OR operator, but you'll usually prefer to use ||
可以用作逻辑OR运算符,但通常更喜欢使用
||
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. 为此,因为后者是一个“短路”操作符,因为如果表达式的左侧是真的,则甚至不评估右侧。
获取当前的Font,使用deriveFont
获取类似于当前的Font但具有新样式的新Font,并应用新字体。
you can do it as follow 你可以这样做
JButton myButton=new JButton();
myButton.setText("My Button");
myButton.setFont(new Font("Serif", Font.BOLD, 14));
As an alternative, you might look at the StyledEditorKit
actions available to JEditorPane
. 作为替代方案,您可以查看
JEditorPane
可用的StyledEditorKit
操作。 There's a related example here and a tutorial here . 有一个相关的例子在这里和教程在这里 。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.