Search code examples
javaswingjtextfield

Changing a JTextField causing exception in cleanup method?


import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;

public class MainForm extends JFrame{

    private JPanel p;
    private JButton clear;
    private JLabel nameLabel;
    private JTextField nameText;
    private JLabel genderLabel;
    private ButtonGroup genderButtonGroup;
    private JTextField courseText;

    public MainForm() {
        super("Some application");
        p = new JPanel();
        this.setLayout(new GridBagLayout());
        GridBagConstraints c = new GridBagConstraints();

        JLabel nameLabel = new JLabel("Student Name");
        c.gridx=0;
        c.gridy=0;
        c.gridwidth=1;
        c.gridheight=1;
        c.weightx=0.0;
        c.weighty=0.0;
        c.fill = GridBagConstraints.VERTICAL;
        c.insets= new Insets(4,4,4,4);
        this.getContentPane().add(nameLabel,c);

        JTextField nameText = new JTextField(20);
        c.gridx=1;
        c.gridy=0;
        c.gridwidth=1;
        c.gridheight=1;
        c.weightx=0.0;
        c.weighty=0.0;
        c.fill = GridBagConstraints.VERTICAL;
        c.insets= new Insets(4,4,4,4);
        this.getContentPane().add(nameText,c);
        nameText.setText("fsdf"); //works fine

        JButton clearButton = new JButton("Clear");
        clearButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { clearMainForm(); } });
        c.gridx=0;
        c.gridy=8;
        c.gridwidth=1;
        c.gridheight=1;
        c.weightx=0.0;
        c.weighty=0.0;
        c.fill = GridBagConstraints.VERTICAL;
        c.insets= new Insets(4,4,4,4);
        this.getContentPane().add(clearButton,c);

    }



    public void clearMainForm() {
        System.out.println("clearing");
        nameText.setText(""); // causes exception
    }



}

changing nameText just after it is created works fine, but trying it in clearMainFOrm, after the clear button is pressed causes an exception.


Solution

  • 1) It helps to actually say what the exception is.

    2) This line:

    JTextField nameText = new JTextField(20);
    

    sets a local variable, not the class variable. Change it to:

    nameText = new JTextField(20);
    

    and it'll work.

    3) You're not setting any of your class variables. You're very shortly going to have more problems.