1
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会导致异常。

4

1 回答 1

2

1)它有助于实际说出异常是什么。

2)这一行:

JTextField nameText = new JTextField(20);

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

nameText = new JTextField(20);

它会起作用的。

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

于 2010-02-15T21:34:43.573 回答