Registered User Registered User - 2 months ago 7
Java Question

TextArea text style does not change to plain from italic in Java

I have two

RadioButton
to select either Italic or Plain Style for a
TextArea
.(They are added to ButtonGroup so only one can be selected)

I have the actionPerformed method as

public void actionPerformed(ActionEvent ae) {
Font currentFont = taText.getFont(); //taText is TextArea
Font fontToSet;
String command = ae.getActionCommand();
if (command.equals("Italic")) {
System.out.println("Italic clicked");
fontToSet = new Font(currentFont.getFontName(),Font.ITALIC,currentFont.getSize());
}
else {
System.out.println("Plain clicked");
fontToSet = new Font(currentFont.getFontName(), Font.PLAIN, currentFont.getSize());
}
taText.setFont(fontToSet);
}


The problem is that when I click on "Italic", the text becomes italic, but when clicking Plain, text does not become plain. Yet the message
Plain Clicked
gets displayed on command line.

What is the problem?

Answer

change your code to

public void actionPerformed(ActionEvent ae) {
    Font currentFont = taText.getFont(); //taText is TextArea
    Font fontToSet;
    String command = ae.getActionCommand();
    if (command.equals("Italic")) {
        System.out.println("Italic clicked");
        fontToSet =currentFont .deriveFont(Font.ITALIC);
    else {
        System.out.println("Plain clicked");
        fontToSet = currentFont .deriveFont(Font.PLAIN);
    }
    taText.setFont(fontToSet);
}

the problem is , getFontName() calls Font2D to get the name and it returns the value based on the current applied styles, but getName() will still return the same font name. but better to use deriveFont();

Comments