0

I have a GUI with a bold and italic JCheckBox as well as a textarea. The layout of my GUI is fine but the functionality of my JCheckBox items are buggy. They are supposed to convert any text in the textarea to bold, italic or both depending on which boxes are ticked. I have managed to make it so that the text is changed to bold when the bold button is ticked initially, but when I deselect it it remains bold, the same goes for my italic button. Here is the implementation for the action listener for my bold button, my italic button uses the same ideas:

class Bold implements ActionListener {

    private final FontSetter fontSetter;
    private final JTextArea textarea;
    private final Font font;
    private final Font font1;
    JCheckBox bold = new JCheckBox("Bold");

    Bold(FontSetter fontSetter, JTextArea textarea) {
        this.fontSetter = fontSetter;
        this.textarea = textarea;
        this.font = new Font(textarea.getText(), Font.BOLD, 12);
        this.font1 = new Font(textarea.getText(), Font.PLAIN, 12);
    }

    public void actionPerformed(ActionEvent e) {
        if (bold.isSelected() == false) {   
            fontSetter.setBold();
            textarea.setFont(font);
        }
        else {
            textarea.setFont(font1);
        }
    }

}

I also have no clue how to check if both the boxes are checked in order to make the text both bold and italic, as oppose to just one or the other, so any suggestions on how I could do this would be appreciated, thanks

DaveRamseyFan
  • 45
  • 2
  • 9

1 Answers1

1

Don't have direct experience with this but to have a font with bold and italic, you need to setup the Font constructor as follows: new Font("", Font.BOLD|Font.ITALIC, 12). Your action performed logic is off. You need a reference to both checkboxes in this class

private JCheckBox _cbBold;
private JCheckBox _cbItalic;

public void actionPerformed(ActionEvent e) {
    int fontStyle = (_cbBold.isSelected ? Font.BOLD : 0) | (_cbItalic.isSelected ? Font.ITALIC : 0);
    Font f = new Font("text area from text", fontStyle, 12);
    //set font on textarea
}
getbuckts
  • 386
  • 1
  • 4