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) 它有助于实际说出异常是什么。
2)这一行:
JTextField nameText = new JTextField(20);
设置局部变量,而不是类变量。将其更改为:
nameText = new JTextField(20);
它会起作用的。
3) 您没有设置任何类变量。很快你就会遇到更多问题。
关于java - 更改 JTextField 导致清理方法出现异常?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2269085/