java - JFrame - 在 GridLayout 中设置行和列

标签 java swing button jframe grid-layout

import java.awt.GridLayout;

import javax.swing.JButton;
import javax.swing.JFrame;

public class GridLayoutTest {

  public static void main(String[] args) {
    JFrame.setDefaultLookAndFeelDecorated(true);
    JFrame frame = new JFrame("GridLayout Test");
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.setLayout(new GridLayout(3, 2));
    frame.add(new JButton("Button 1"));
    frame.add(new JButton("Button 2"));
    frame.add(new JButton("Button 3"));
    frame.add(new JButton("Button 4"));
    frame.add(new JButton("Button 5"));
    frame.add(new JButton("Button 6"));
    frame.add(new JButton("Button 7"));
    frame.add(new JButton("Button 8"));
    frame.pack();
    frame.setVisible(true);
  }
}

我从本教程网站获得了代码:http://www.java2s.com/Tutorial/Java/0240__Swing/HowtoUseGridLayout.htm

该程序在屏幕上显示 8 个按钮。我无法理解按钮的布局安排。请注意,行=3,列=2。当我运行程序时,按钮的排列是row=3和column=3....

更改行数实际上会根据给定的行号更改布局,但更改列数不会更改布局,列数将始终保持为 2。这是为什么?这可能是屏幕尺寸问题。

最佳答案

这是 GridLayout 类的记录行为。你有吗read the docs?

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.

“仅当行数设置为零时,指定列数才会影响布局。”因此,如果您希望保持列数不变,请为行指定 0:

    frame.setLayout(new GridLayout(0, 2));

关于java - JFrame - 在 GridLayout 中设置行和列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26092495/

相关文章:

java - 使用 JASYPT + Hibernate + Spring 进行字符串加密

Java 子类属性是否绑定(bind)?

javascript - 单击按钮时停止页面重新加载

java - 通过 Spring Controller 映射图像文件

java - 如何获得与通配符 css 选择器匹配的第二个元素?

java - Spring Security简单应用

android - 在代码中设置ListView行高

java - 鼠标滑过 JLabel 时不显示文本

java - 如何使用 BorderLayout 扩展 JTextField (Java)

javascript - 空事件监听器 : Is this ok?