[JavaSwing] 的FlowLayout
正如你所知道的集装箱 (作为JFrame中, 的JPanel, ...) 用于存储的控制其, 然而,他们可能会或可能不会默认对象的安排是不是我们所期望的. 因此,我们需要利用这样做布局. 换句话说,布局帮助下,我们可以安排容器以合理的方式和美丽.
注意你从邮编小时可长, 所以我只评论有关,但没有提及全部或部分的主题部分. 与其它部件即没有评论在上一篇文章中提到过,然后, 你可以找到通过键入关键字的博客在搜索框中.
的FlowLayout 是对象的在一条线上的排列, 从左至右. 我们使用的FlowLayout,当你想组织一起上连续的直线对象.
创建并把集装箱的FlowLayout
下面的例子将创建并把对的FlowLayout 的JPanel 包含 JButton的 人物:

package nguyenvanquan7826.FlowLayout;
import java.awt.ComponentOrientation;
import java.awt.FlowLayout;
import java.awt.LayoutManager;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class MyFlowLayout extends JFrame implements ActionListener {
private String buttonName[] = { "FlowLayout", "add", "controls", "in",
"the", "line" };
public MyFlowLayout() {
createJFrame();
}
// create and display JFrame
private void createJFrame() {
setTitle("My FlowLayout");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setSize(550, 200);
// add panel content to JFrame
add(createJPanelContent());
setLocationRelativeTo(null);
setVisible(true);
}
// add content in JFrame
private JPanel createJPanelContent() {
// create FlowLayout
FlowLayout layout = new FlowLayout(FlowLayout.RIGHT, 10, 20);
// create a JPanel container control (JButton)
JPanel panel = new JPanel(layout);
// add array JButton to panel
for (int i = 0; i < buttonName.length; i++) {
panel.add(createJButton(buttonName[i]));
}
return panel;
}
// create JButton
private JButton createJButton(String buttonName) {
JButton btn = new JButton(buttonName);
btn.addActionListener(this);
return btn;
}
@Override
public void actionPerformed(ActionEvent evt) {
String command = evt.getActionCommand();
for (int i = 0; i < buttonName.length; i++) {
if (command == buttonName[i]) {
System.out.println(buttonName[i]);
}
}
}
public static void main(String[] args) {
new MyFlowLayout();
}
}
构造函数的FlowLayout包括:
– 的FlowLayout(): FlowLayout中初始化对象对齐默认CENTER (中心) 和之间的距离由默认水平和垂直方向的对象 5 单元.
– 的FlowLayout(INT对齐): 同上,但我们只对齐的位置: 中央, 剩下, 对, 领导, TRAILING (领导, TRAILIN并显示了左平, 相对于所述装置根据容器, 在参考 LEFT和领导的区别, RIGHT VA TRAILING).
– 的FlowLayout(INT对齐, 参数hgap, INT vgap): 有了这个初始化,我们将设置对齐和水平距离的方式 (hgap指定), 纵 (vgap) 对象之间.

默认情况下的JPanel使用默认的FlowLayout (中心对齐, 距离hgap指定= vgap = 5) 所以我创建 1 新的布局左平 (对), 水平的物体之间的距离 10, 纵是 20. 当调整的JFrame不足的宽度包含上,它们将自动地被推动至底线JButton的如下所示.
请参阅: 一流的FlowLayout, 使用FlowLaout



1 在回应 [JavaSwing] 的FlowLayout