尝试在我正在制作的简单 GUI 中预实例化 JTextField 数组。我将它们放入一个数组中,以便当我更改状态时,我可以循环它们并使用简单的 for 循环清除数据。在我在构造函数中实例化窗口中使用的每个对象后,程序崩溃了。我已经包含了声明数组和 5 个按钮对象的 2 行。我还包括如何实例化每个文本字段。 代码在调用我的清除方法时崩溃,空指针异常。经过仔细检查,我发现我的 fields[0] 到 fields[4] 均为空。我不知道为什么。 tf1 到 tf5 不为空
//instantiation of fields t1, t2, t3, t4, t5 and fields array
private JTextField tf1, tf2, tf3, tf4, tf5;
private JTextField[] fields = {tf1, tf2, tf3, tf4, tf5};
//In the constructor
tf1 = new JTextField();
//clear method called after all objects are instantiated
private void clear() { for(JTextField f : fields) f.setText(""); }
预期 fields[0] 具有与 tf1 相同的值,但为 null;
最佳答案
观察以下代码:
public class Main
{
public static void main(String[] args)
{
Main m = null;
var ms = new Main[]{m};
m = new Main();
System.out.println(m);
System.out.println(ms[0]);
}
}
输出:
Main@5acf9800
null
数组在创建时不保留对变量的引用。相反,它们会及时复制该时刻的引用值。即使引用的值发生变化,数组中的值也保持不变。
如果您不希望更改数组(根本),您可以执行如下操作:
//instantiation of fields t1, t2, t3, t4, t5 and fields array
private JTextField tf1, tf2, tf3, tf4, tf5;
private JTextField[] fields;
//In the constructor
tf1 = new JTextField();
//instantiate the others as well if you'd like
fields = new JTextField[] {tf1, tf2, tf3, tf4, tf5};
//clear method called after all objects are instantiated
private void clear() { for(JTextField f : fields) f.setText(""); }
...
// anytime you update tf1 later, update fields[0].
// anytime you update tf2 later, update fields[1].
// ... ... ...
通常最好只保留变量,或者只保留数组/集合。管理一组变量已经够烦人的了;为什么要创建两套让自己变得更困难?
关于Java预实例化数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58242830/