我正在我的 Java 类上开发一个应用程序,但遇到了一个奇怪的问题。我需要在网格中表示数据,因此使用GridLayout是一个明显的选择,但这里有一个问题。我继续得到几乎空的框架(注意左上角的小白色矩形)。
这是产生此结果的代码片段
//not important class code
public static void main(String args[]) {
JFrame frame = new JFrame("Wolves & Rabbits");
frame.setSize(640, 480);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
//want to create a 12x9 grid with 2 black and 4 pink rectangles
Board board = new Board(12, 9, 2, 4, 1000);
frame.add(board);
frame.setResizable(false);
frame.setVisible(true);
}
//Board.java (Board class) extends JPanel
public JPanel fields[][];
private Integer boardWidth, boardHeight;
private ArrayList<AnimalThread> animals;
private Integer wolvesCount, rabbitsCount;
public Board(int w, int h) {
super(new GridLayout(h, w, 4, 4));
fields = new JPanel[w][h];
boardWidth = new Integer(w);
boardHeight = new Integer(h);
animals = null;
wolvesCount = new Integer(0);
rabbitsCount = new Integer(0);
//creating white rectangles
for (int i = 0; i < boardHeight; i++)
for (int j = 0; j < boardWidth; j++) {
fields[j][i] = new JPanel(true);
fields[j][i].setBackground(AnimalThread.NONE);
this.add(fields[j][i]);
}
AnimalThread.setLinkToBoard(this);
}
public Board(int w, int h, int wolves, int rabbits, int k) {
this(w, h);
animals = new ArrayList<AnimalThread>();
while (boardWidth*boardHeight < 2*wolves*rabbits) {
wolves--;
rabbits--;
}
wolvesCount = wolves;
rabbitsCount = rabbits;
WolfThread.setRabbitsCount(rabbitsCount);
//randomly place colored rectangles
this.randomize(wolves, rabbits, k);
}
奇怪的是,根本没有改变 Board 类,只对 main 方法做了一点改变,我就能够显示正确的网格。
在这种情况下,主要方法是
//not important class code
public static void main(String args[]) {
JFrame frame = new JFrame("Wolves & Rabbits");
frame.setSize(640, 480);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
Board board = new Board(12, 9, 2, 4, 1000);
//THE CHANGE!
JPanel panel = new JPanel(new GridLayout(12, 9, 4, 4));
for (int i = 0; i < 9; i++)
for (int j = 0; j < 12; j++) {
JPanel tmp = board.fields[j][i];
panel.add(tmp);
}
frame.add(panel);
frame.setResizable(false);
frame.setVisible(true);
}
任何人都知道是什么导致了这个恼人的问题?任何线索将不胜感激。