J0n*_*Lam 3 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);
}
}
Run Code Online (Sandbox Code Playgroud)
我从这个教程网站得到了代码:http : //www.java2s.com/Tutorial/Java/0240__Swing/HowtoUseGridLayout.htm
该程序在屏幕上显示 8 个按钮。我无法理解按钮的布局安排。注意 row=3,column=2。当我运行程序时,按钮的排列是row=3和column=3....
改变行数实际上会根据给定的行数改变布局,但改变列数并不会改变布局,列数将始终保持为 2。这是为什么呢?可能是屏幕尺寸问题。
这是GridLayout该类的记录行为。你读过文档吗?
当行数和列数都被构造函数或 setRows 和 setColumns 方法设置为非零值时,指定的列数将被忽略。 相反,列数由指定的行数和布局中的组件总数确定。因此,例如,如果指定了三行两列,并且在布局中添加了九个组件,它们将显示为三行三列。仅当行数设置为零时,指定列数才会影响布局。
“仅当行数设置为零时,指定列数才会影响布局。” 因此,如果要保持列数不变,请为行指定 0:
frame.setLayout(new GridLayout(0, 2));
Run Code Online (Sandbox Code Playgroud)