设置FlowLayout流水布局
时间: 2023-07-01 19:13:31 浏览: 62
要将Java窗口的布局设置为FlowLayout流水布局,可以使用以下代码:
```java
import javax.swing.JButton;
import javax.swing.JFrame;
import java.awt.FlowLayout;
public class Main {
public static void main(String[] args) {
JFrame frame = new JFrame("计算");
frame.setLayout(new FlowLayout());
frame.add(new JButton("按钮1"));
frame.add(new JButton("按钮2"));
frame.add(new JButton("按钮3"));
frame.pack();
frame.setVisible(true);
}
}
```
在这个示例中,我们创建了一个名为 `frame` 的 `JFrame` 对象,并将其布局设置为FlowLayout流水布局。然后,我们向该窗口中添加了三个按钮,并通过 `pack()` 方法使窗口自适应按钮的大小。最后,我们调用 `frame.setVisible(true)` 方法来使窗口可见。
注意:FlowLayout默认的对齐方式是居中对齐。如果你想要修改对齐方式,可以在创建FlowLayout对象时传入对应的对齐方式,例如:
```java
frame.setLayout(new FlowLayout(FlowLayout.LEFT)); // 左对齐
frame.setLayout(new FlowLayout(FlowLayout.RIGHT)); // 右对齐
frame.setLayout(new FlowLayout(FlowLayout.CENTER)); // 居中对齐
```