Search code examples
javauser-interfacejtextfield

setting text to bold using java


I am creating a GUI with some JCheckButtons (bold italic), these buttons will turn the text in the text field to bold, italic or both when selected through the use of action listeners. Here is how I implement this functionality in my action listener methods (this is for the bold method, I also have similar methods for italic and bold and italic).

class Bold implements ActionListener {

    private final FontSetter fontSetter;
    private final JTextField textfield;

    Bold(FontSetter fontSetter, JTextField textfield) {
        this.fontSetter = fontSetter;
        this.textfield = textfield;
    }

    Font font = new Font(textfield.getText(), Font.BOLD,12);

    public void actionPerformed(ActionEvent e) {
        fontSetter.setBold();
        textfield.setFont(font);
    }

}

error: the blank final field textfield may not have been initialised,how can I fix this?


Solution

  • You have to initialize the textfield variable first before you use it. Since you have defined font as another instance variable, the reference to textfield may not have been initialized yet.

    One possible approach is to initialize font on construction since it is dependent on textfield:

    private final JTextField fontSetter;
    private final JTextField textfield;
    private final Font font;
    
    Bold(JTextField fontSetter, JTextField textfield) {
        this.fontSetter = fontSetter;
        this.textfield = textfield;
        this.font = new Font(textfield.getText(), Font.BOLD, 12);
    }