我正在使用Java(ver1.42) awt来制作聊天程序
我制作了粗体和斜体JCheckBox
来更改JTextArea
中的字体。
这是 2 个复选框的监听器。
class CheckBoxListener implements ChangeListener {
public void stateChanged(ChangeEvent ce) {
String fontName = inputTextArea.getFont().getFontName();
int fontSize = inputTextArea.getFont().getSize();
int fontStyle = 0;
if(boldCheckBox.isSelected())
fontStyle += Font.BOLD;
if(italicCheckBox.isSelected())
fontStyle += Font.ITALIC;
inputTextArea.setFont(new Font(fontName, fontStyle, fontSize));
}
}
}
一切顺利
如果我选中“boldCheckBox”,inputTextArea
中的字体将更改为 BOLD。
如果我选中“italicCheckBox”,inputTextArea
中的字体将更改为 ITALIC。
以及
如果我取消选中“italicCheckBox”,字体将变为正常形式。
但是
即使我取消选中“boldCheckBox”,字体也不会回来
你能找出问题所在吗?
最佳答案
首先,您确实必须使用按位 |
运算符将粗体和斜体以相同的字体组合在一起,而不是 +
运算符。
也可能是这样的情况:一旦您切换到粗体字体,系统就会使用包含粗体属性的相关字体。例如,在某些操作系统中,您有“Arial”和“ArialBD”。由于您是根据旧字体的名称而不是使用 deriveFont 创建新字体,因此它可能仍然是“ArialBD”。
所以试试这个:
class CheckBoxListener implements ChangeListener {
public void stateChanged(ChangeEvent ce) {
int fontStyle = Font.PLAIN;
if(boldCheckBox.isSelected())
fontStyle |= Font.BOLD;
if(italicCheckBox.isSelected())
fontStyle |= Font.ITALIC;
inputTextArea.setFont(inputTextArea.getFont().deriveFont(fontStyle));
}
}
}
关于java - ChangeListener 不会更改 JTextArea 中的字体,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26501730/