Java - 异常的 GridLayout 行为

标签 java swing jbutton jlabel grid-layout

只是在摆弄 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/

相关文章:

java - 将文本粘贴到 JTextComponent 后获取操作 (Java)

java - 为按钮添加边框使其变小

java - 方法的局部变量是否被线程共享?

java - fragment 中的 Tablayout bundle - 空对象引用

java - drawString 和 Ellipse2D 兼容性问题

java - 更新/重新创建 JList

Java Swing 问题,为什么changeEvent 使用jButton 触发额外的事件?

java - 如何将 SOAP 响应安全地存储在数据库中?

java - 操作系统(linux)如何杀死java程序?当我硬终止一个 java 进程时,jvm 会发生什么?

java - 如何解决 ,"AWT-EventQueue-0"java.lang.IndexOutOfBoundsException : Index: 0, 大小:0