Java6学习笔记11——利用Swing的Boxlayout

import javax.swing.JFrame;
import javax.swing.JButton;
import javax.swing.BoxLayout;
import javax.swing.Box;
import java.awt.Container;
import java.awt.Component;
import java.awt.Dimension;
import java.awt.event.WindowEvent;
import java.awt.event.WindowAdapter;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;

public class VerticalBox3 extends JFrame implements ActionListener {
public static void main(String arg[]) {
new VerticalBox3();
}
public VerticalBox3() {
addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
System.exit(0);
}
} );
buildFrame();
setLocation(250,150);
setVisible(true);
}
private void buildFrame() {
JButton button;

Container pane = getContentPane();
BoxLayout boxlayout = new BoxLayout(pane,BoxLayout.Y_AXIS);
pane.setLayout(boxlayout);

pane.add(Box.createRigidArea(new Dimension(100,10)));//设置上下左右的间距
button = new JButton("First");
button.setAlignmentX(Component.CENTER_ALIGNMENT);//设置居中
setSize(button);
pane.add(button);
pane.add(Box.createRigidArea(new Dimension(100,10)));
button = new JButton("Second");
button.setAlignmentX(Component.CENTER_ALIGNMENT);
setSize(button);
pane.add(button);
pane.add(Box.createRigidArea(new Dimension(100,10)));
button = new JButton("Third");
button.setAlignmentX(Component.CENTER_ALIGNMENT);
setSize(button);
pane.add(button);
pane.add(Box.createRigidArea(new Dimension(100,10)));
button = new JButton("Fourth");
button.setAlignmentX(Component.CENTER_ALIGNMENT);
setSize(button);
pane.add(button);
pane.add(Box.createRigidArea(new Dimension(100,10)));
button = new JButton("Exit");
button.addActionListener(this);
button.setAlignmentX(Component.CENTER_ALIGNMENT);
setSize(button);
pane.add(button);
pane.add(Box.createRigidArea(new Dimension(100,10)));

pack();
}
private void setSize(Component comp) {
comp.setPreferredSize(new Dimension(80,25));//设置最大、最小和合适的大小相同
comp.setMaximumSize(new Dimension(80,25));
comp.setMinimumSize(new Dimension(80,25));
}
public void actionPerformed(ActionEvent e) {
String selection = e.getActionCommand();
if(selection.equals("Exit")) {
System.exit(0);
}
}
}

你可能感兴趣的:(java,swing)