嗨,我想让字母 x 出现在第 1-4 行,字母 y 出现在第 7-10 行。出于某种原因,当我放置 else 而不是 else 时,它会起作用,如果这样,除了 1-4 之外的每一行都得到“y”。它标记了 else 已读并说要删除此令牌并说 Null Pointer Exception 我在第 26 行收到错误,即带有 frame.add 的错误
import java.awt.Color;
import java.awt.GridLayout;
import java.util.Random;
import java.util.Scanner;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JTextField;
public class ButtonGrid {
JFrame frame=new JFrame();
JButton[][] grid;
public ButtonGrid(int width, int length){
Random r=new Random();
int w=r.nextInt(13-1)+1;
frame.setLayout(new GridLayout(width,length));
grid=new JButton[width][length];
Scanner g = new Scanner(System.in);
for(int y=0;y<length;y++){
for(int x=0;x<width;x++){
if (y < 4) {
grid[x][y]=new JButton("x");-I am trying to set lines 1-4 to x
}
else if (y>7){
grid[x][y]=new JButton("y");-I am trying to set lines 7-10 to y
}
frame.add(grid[x][y]);
else{ "IT MARKS THIS AS WRONG"
grid[x][y]=new JButton(" ");
}
}
}
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.pack();
frame.setVisible(true);``
}
public static void main(String[] args) {
new ButtonGrid(10,10);
}
}
我认为我所做的一切都是正确的,只是不确定为什么 eclipse 会给我这些错误。请帮忙!最终我将在第 7-10 行输入,但这个测试不起作用。如果有人知道如何帮助我,我正在 Swing 中玩棋盘游戏 Stratego。