setLayout(new GridLayout(1,4));
add(new JButton("B1"));
add(new JButton("B2"));
add(new JButton("B3"));
add(new JButton("B4"));
//布局的例子
//:LayoutTest.java
import java.awt.Container;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
public class LayoutTest {
public static void main(String[] args){
final JFrame f = new JFrame();
Container c = f.getContentPane();
//布局设为空,意味著用户能自由地将组件根据其自身大小和位置放入容器中
c.setLayout(null);
JButton b1 = new JButton("1");
JButton b2 = new JButton("2");
JButton b3 = new JButton("3");
JButton b4 = new JButton("4");
int w,h,x,y;
w=42;
h=22;
x=20;
y=20;
//设置b1的大小
b1.setSize(w,h);
//设置b1的位置
b1.setLocation(x,y);
//可以直接如下设置
//b1.setBounds(x, y, w, h);
c.add(b1);
x=70;
b2.setSize(w,h);
b2.setLocation(x,y);
c.add(b2);
x=120;
b3.setBounds(x,y,w,h);
c.add(b3);
x=170;
y=y+10;//这里我改变了Y的值,很随意的
b4.setBounds(x,y,w,h);
c.add(b4);
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.setSize(240,100);
f.setResizable(false);
f.setLocationRelativeTo(null);
f.setVisible(true);
//
ActionListener l = new ActionListener(){
public void actionPerformed(ActionEvent e) {
Object o = e.getSource();
JButton b = (JButton)o;
//如果 f 未被 final修饰,这里就不能编译通过
f.setTitle(b.getText()+" clicked.");
}
};
b1.addActionListener(l);
b2.addActionListener(l);
b3.addActionListener(l);
b4.addActionListener(l);
//final JFrame f = ...
//意思是 f 的引用是不能变的
//特别是局部变量要被内隐类"直接"调用时,这个局部变量就得用final修饰
}
}