I'm using Java(ver1.42) awt for making chatting program
I made bold & Italic JCheckBox
to change font in JTextArea
.
Here is the listener for 2 CheckBoxes.
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));
}
}
}
Everything works well
If I check "boldCheckBox", font in inputTextArea
changes into BOLD.
If I check "italicCheckBox", font in inputTextArea
changes into ITALIC.
AND
If I un-check "italicCheckBox", font changes into normal form.
HOWEVER
font never comes back even though I un-checked "boldCheckBox"
could you find what's wrong?
First, indeed you have to use the bitwise |
operator to get Bold and Italic together in the same font, not the +
operator.
It could also be the case that the system, once you have switched to a bold font, is using a related font that includes the bold attribute. For example, in some operating systems, You have "Arial" and "ArialBD". Since you create your new font based on the name of the old font rather than using deriveFont
, it may be that it stays "ArialBD".
So try this:
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));
}
}
}