在清理方法中更改导致异常的JTextField?

时间:2010-02-15 21:32:41

标签: java swing jtextfield

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
    }



}

在创建它之后更改nameText工作正常,但在按下清除按钮后在clearMainFOrm中尝试它会导致异常。

1 个答案:

答案 0 :(得分:2)

1)实际说明异常是什么有帮助。

2)这一行:

JTextField nameText = new JTextField(20);

设置局部变量,而不是类变量。将其更改为:

nameText = new JTextField(20);

它会起作用。

3)您没有设置任何类变量。你很快就会遇到更多问题。