In my applet program I have the TextField declared in my public class header as:
TextField numbers [][] = new TextField[5][5];
I also have a button that is supposed to clear all the textboxes when clicked.
Right now I basically have this:
JButton b = new JButton("Clear");
b.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
numbers.setText("");
}
});
But I'm getting an error: "Cannot invoke setText(null) on the array type TextField[][]"
How can I fix this?
Key lesson here: read the error message critically as it is telling you exactly what is wrong.
"Cannot invoke setText(null) on the array type TextField[][]"
You're treating the numbers variable as if it's a single TextField and it's not, and so you can't call setText(...)
on it -- rather it's a 2D array of objects. A solution is to think of how you interact with any similar 2-d array, how do you call methods on each item held within the array: use nested for loops to iterate through the array.
for (int i = 0; i < numbers.length; i++) {
for (int j = 0; j < numbers[i].length; j++) {
numbers[i][j].setText("");
}
}
Also, change TextField to JTextField so that you're using all Swing components:
// change type from TextField to JTextField
JTextField numbers [][] = new JTextField[5][5];
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.