我正在尝试创建一个创建9x9文本字段数组的程序,然后当按下某个按钮时,将打印包含数字的所有文本字段,并且所有空文本字段都会打印错误“text field”是空的”。但是,我收到一个错误,说变量必须是最终的。我假设这个程序假定数组“字段”尚未确定。
public static void initialize() {
JFrame frame = new JFrame();
frame.setSize(316, 400);
frame.setVisible(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().setLayout(null);
JButton btnNewButton = new JButton("New button");
frame.getContentPane().add(btnNewButton);
btnNewButton.setBounds(1, 320, 310, 35);
int X;
int Y;
int XPosition = 21; // x location of textField
int YPosition = 21; // y location of textField
int[][] squares = new int[9][9];
TextField[][] fields = new TextField[9][9];
{
for (Y = 0; Y < 9; Y++) {
XPosition = 0;
for (X = 0; X <= 8; X++) {
fields[X][Y] = new TextField(1);
fields[X][Y].setColumns(1);
fields[X][Y].setBounds(XPosition, YPosition, 32, 32);
frame.getContentPane().add(fields[X][Y]);
XPosition = XPosition + 32;
}
YPosition = YPosition + 32;
}
}
btnNewButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
if (fields[1][1].getText().isEmpty()) {
System.out.println(field[X][Y] + " is empty");
} else {
for (int Y = 0; Y < 9; Y++) {
for (int X = 0; X <= 8; X++) {
System.out.println(fields[1][1].getText());
squares[X][Y] = Integer.parseInt((fields[X][Y].getText()));;
}
}
}
}
});
}
答案 0 :(得分:-1)
你可以通过使X和Y成为具有2个元素的最终数组来“修复”它。数组本身是最终的,但您可以随时更改其中的元素。
public static void initialize() {
JFrame frame = new JFrame();
frame.setSize(316, 400);
frame.setVisible(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().setLayout(null);
JButton btnNewButton = new JButton("New button");
frame.getContentPane().add(btnNewButton);
btnNewButton.setBounds(1, 320, 310, 35);
final int fix[] = {0,0};
fix[0] = 0;
fix[1] = 0;
int XPosition = 21; // x location of textField
int YPosition = 21; // y location of textField
int[][] squares = new int[9][9];
TextField[][] fields = new TextField[9][9];
{
for (fix[1] = 0; fix[1] < 9; fix[1]++) {
XPosition = 0;
for (fix[0] = 0; fix[0] <= 8; fix[0]++) {
fields[fix[0]][fix[1]] = new TextField(1);
fields[fix[0]][fix[1]].setColumns(1);
fields[fix[0]][fix[1]].setBounds(XPosition, YPosition, 32, 32);
frame.getContentPane().add(fields[fix[0]][fix[1]]);
XPosition = XPosition + 32;
}
YPosition = YPosition + 32;
}
}
btnNewButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
if (fields[1][1].getText().isEmpty()) {
System.out.println(fields[fix[0]][fix[1]] + " is empty");
} else {
for (int Y = 0; Y < 9; Y++) {
for (int X = 0; X <= 8; X++) {
System.out.println(fields[1][1].getText());
squares[X][Y] = Integer.parseInt((fields[X][Y].getText()));;
}
}
}
}
});
}