[JavaSwing] BoxLayout的在Java中
正如你所知道的集装箱 (作为JFrame中, 的JPanel, ...) 用于存储的控制其, 然而,他们可能会或可能不会默认对象的安排是不是我们所期望的. 因此,我们需要利用这样做布局. 换句话说,布局帮助下,我们可以安排容器以合理的方式和美丽.
的BoxLayout布局允许我们进行排序控制的上一个水平或垂直柱.
当我们横向排列,其他具有FlowLayout, 控制不会自动倒行了,如果没有足够的空间让他们.
例如,创建和使用的BoxLayout
我们将有一系列的JButton的, 含 1 JButton的改变,让我们从横向切换显示,以垂直和反之亦然.
package nguyenvanquan7826.BoxLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.BoxLayout;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class MyBoxLayout extends JFrame {
private JPanel mainPanel;
private BoxLayout boxLayout;
private boolean axis = true;
public MyBoxLayout() {
createJFrame();
}
private void createJFrame() {
// create JFrame
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setSize(400, 200);
// add content
mainPanel = createMainPanel();
add(mainPanel);
// display
setLocationRelativeTo(null);
setVisible(true);
}
private JPanel createMainPanel() {
// create panel with BoxLayout
JPanel panel = new JPanel();
boxLayout = new BoxLayout(panel, BoxLayout.X_AXIS);
panel.setLayout(boxLayout);
// add button change to main panel
JButton btnChange = new JButton("Change");
btnChange.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent arg0) {
change();
}
});
panel.add(btnChange);
// add list button to main panel
for (int i = 0; i < 5; i++) {
panel.add(new JButton("Button" + i));
}
return panel;
}
// change axis when click button change
private void change() {
int ax = axis ? BoxLayout.Y_AXIS : BoxLayout.X_AXIS;
// reset boxLayout
boxLayout = new BoxLayout(mainPanel, ax);
// set boxLayout to mainPanel
boxLayout.layoutContainer(mainPanel);
axis = !axis;
}
public static void main(String[] args) {
new MyBoxLayout();
}
}

你可以,我们刚刚创建的JPanel上一节中发现, 布局设置为它是正确的形式:
[的JPanel面板=的新JPanel(新的布局管理());
但随着BoxLayout的,我们不能这样做,因为BoxLayout构造是有我们的集装箱.
的BoxLayout(集装箱的目标, INT轴): 创建的BoxLayout布局轴线.
因此,我们需要初始化容器 (的JPanel) 前, 然后初始化BoxLayout的最后使用的功能 的setLayout 布局设置的JPanel.
对象的排列垂直或水平取决于该参数轴线, X_AXIS可以水平排列, Y_AXIS是垂直.
更新…



最新评论