當我運行我的代碼時,JFrame窗口顯示標題框架的最小可能版本,它需要調整大小以實際顯示任何內容。 通常這是由於最後缺少pack()或setVisible(true),但在這種情況下不是。 這是代碼:Java - JLabel組件僅在調整大小時顯示
public static void main(String[] args) throws FileNotFoundException {
Boolean[][] maze = Exercise4.readMaze();
int row = maze.length;
JFrame f = new JFrame("Maze");
f.setLayout(new GridLayout(row, row));
for (int i = 0; i < row; i++) {
for (int j = 0; j < row; j++) {
JLabel grid = new JLabel();
grid.setOpaque(true);
if (maze[i][j].equals(false))
grid.setBackground(Color.black);
else grid.setBackground(Color.white);
f.add(grid);
}
}
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.pack();
f.setVisible(true);
}
這會給它一個大小,並在屏幕上顯示一些東西 - 但也要注意,你不應該直接添加組件到JFrame--你應該將它們添加到框架的內容窗格('JFrame.getContentPane()' ) –
@ErwinBolwidt從何時起? Java 1.5提供了自動調用'contentPane'的'add'(和'remove'')的功能 - 這是人們期待的主要功能之一(在Swing中)。我個人而言,我會使用'JPanel'作爲基礎組件,並將其添加到我需要的任何容器中 - 但我認爲此時可能超出了OP的範圍:P – MadProgrammer
酷,很好了解。從來沒有必要重新討論,因爲使用'getContentPane()'進行了充分的鑽取,但我看到了JFrame現在的功能。 –