如何清除数组中的 TextField?
How to clear TextField in an array?
在我的小程序程序中,我在 public class header 中将 TextField 声明为:
TextField numbers [][] = new TextField[5][5];
我还有一个按钮,点击后应该会清除所有文本框。
现在我基本上是这样的:
JButton b = new JButton("Clear");
b.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
numbers.setText("");
}
});
但是我收到一个错误:"Cannot invoke setText(null) on the array type TextField[][]"
我该如何解决这个问题?
这里的关键教训:批判性地阅读错误消息,因为它告诉你到底出了什么问题。
"Cannot invoke setText(null) on the array type TextField[][]"
您将 numbers 变量视为单个 TextField 而不是,因此您不能对其调用 setText(...)
-- 相反它是一个二维对象数组。一个解决方案是考虑如何与 any 类似的二维数组交互,如何调用数组中保存的每个项目的方法:使用嵌套的 for 循环遍历数组。
for (int i = 0; i < numbers.length; i++) {
for (int j = 0; j < numbers[i].length; j++) {
numbers[i][j].setText("");
}
}
此外,将 TextField 更改为 JTextField,以便您使用所有 Swing 组件:
// change type from TextField to JTextField
JTextField numbers [][] = new JTextField[5][5];
在我的小程序程序中,我在 public class header 中将 TextField 声明为:
TextField numbers [][] = new TextField[5][5];
我还有一个按钮,点击后应该会清除所有文本框。
现在我基本上是这样的:
JButton b = new JButton("Clear");
b.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
numbers.setText("");
}
});
但是我收到一个错误:"Cannot invoke setText(null) on the array type TextField[][]"
我该如何解决这个问题?
这里的关键教训:批判性地阅读错误消息,因为它告诉你到底出了什么问题。
"Cannot invoke setText(null) on the array type TextField[][]"
您将 numbers 变量视为单个 TextField 而不是,因此您不能对其调用 setText(...)
-- 相反它是一个二维对象数组。一个解决方案是考虑如何与 any 类似的二维数组交互,如何调用数组中保存的每个项目的方法:使用嵌套的 for 循环遍历数组。
for (int i = 0; i < numbers.length; i++) {
for (int j = 0; j < numbers[i].length; j++) {
numbers[i][j].setText("");
}
}
此外,将 TextField 更改为 JTextField,以便您使用所有 Swing 组件:
// change type from TextField to JTextField
JTextField numbers [][] = new JTextField[5][5];