运行布局的效果:
布局图示:
import java.awt.Component;
import java.awt.Container;
import java.awt.Dimension;
import javax.swing.Box;
import javax.swing.JApplet;
import javax.swing.JButton;
import javax.swing.JLabel;
import javax.swing.JTextArea;
import javax.swing.JTextField;
public class BoxLayoutDemo01 extends JApplet
{
public void init()
{
Container cp = getContentPane();
this.setSize(600, 200);
Box bBox = Box.createHorizontalBox();
cp.add(bBox);
Box vBox = Box.createVerticalBox();
JLabel lb = new JLabel("这是标签");
vBox.add(lb);
JButton bt1 = new JButton("这是按钮1");
bt1.setMaximumSize(new Dimension(100,30));
vBox.add(bt1);
bBox.add(vBox);
Box vBox2 = Box.createVerticalBox();
bBox.add(vBox2);
JTextField tf1 = new JTextField("这是文本框",10);
tf1.setAlignmentX(Component.CENTER_ALIGNMENT);
tf1.setMaximumSize(new Dimension(150,50));
vBox2.add(tf1);
Box vBox2h = Box.createHorizontalBox();
vBox2.add(vBox2h);
Box vBox2h1 = Box.createVerticalBox();
vBox2h1.add(Box.createVerticalStrut(20));
vBox2h1.add(new JTextArea("这是文本区域",15,10));
vBox2h1.add(Box.createVerticalStrut(20));
vBox2h.add(vBox2h1);
Box vBox2h2 = Box.createVerticalBox();
vBox2h2.add(new JButton("这是按钮2"));
vBox2h2.add(Box.createVerticalGlue());
vBox2h2.add(new JButton("这是按钮4"));
vBox2h.add(vBox2h2);
vBox2h.add(Box.createHorizontalGlue());
}
}