只是在摆弄 Swing,想知道为什么当 GridLayout 定义为 10 行 10 列时,下面的代码构造了一个看起来只有三列的布局?
谁能解释这种不寻常的行为以及所提供的代码中是什么导致了这种情况发生?
public class MyGrid {
public static void main (String[] args) {
JFrame frame = new JFrame();
Container container = frame.getContentPane();
container.setLayout(new GridLayout(10,10));
for (int i = 0; i < 5; i++) {
for (int j = 0; j < 5; j++) {
if (i>=j) {
container.add(new JButton("X"));
} else {
container.add(new JLabel("Y"));
}
}
}
frame.setSize(500,500);
frame.setVisible(true);
}
}
最佳答案
参见 GridLayout
的类 javadoc :
When both the number of rows and the number of columns have been set to non-zero values, either by a constructor or by the setRows and setColumns methods, the number of columns specified is ignored. Instead, the number of columns is determined from the specified number of rows and the total number of components in the layout. So, for example, if three rows and two columns have been specified and nine components are added to the layout, they will be displayed as three rows of three columns. Specifying the number of columns affects the layout only when the number of rows is set to zero.
如果您使用此代码
public class MyGrid {
public static void main (String[] args) {
JFrame frame = new JFrame();
Container container = frame.getContentPane();
container.setLayout(new GridLayout(10,10));
for ( int i =0; i < 100; i++ ){
container.add( new JLabel( ""+i ) );
}
frame.setSize(500,500);
frame.setVisible(true);
}
}
您会看到 10 行和 10 列。如果你使用 i < 50
例如在 for 循环中,列数发生变化。
关于Java - 异常的 GridLayout 行为,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10258570/