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 に答える