java基础:GUI基础编程(下)(二)

2014-11-24 01:34:25 · 作者: · 浏览: 7
我是按钮b1.");
b2=new JButton("我是按钮b2");
tf=new JTextField("我是文本框");
l1=new JLabel("我是一个标签");
l2=new JLabel("我是另一个标签");
//布局JTextArea
gbc.weightx=0;//指定如何分布额外的水平空间
gbc.weighty=0;//指定如何分布额外的垂直空间
//BOTH:在水平方向和垂直方向上同时调整组件大小
//fill:当组件的显示区域大于它所请求的显示区域的大小时使用此字段
gbc.fill=GridBagConstraints.BOTH;
addComponent(ta,gbl,gbc,0,0,1,3);
//布局按钮b1
gbc.fill=GridBagConstraints.HORIZONTAL;
addComponent(b1,gbl,gbc,1,0,2,1);
//布局按钮b2
gbc.fill=GridBagConstraints.HORIZONTAL;
addComponent(b2,gbl,gbc,1,1,2,1);
setVisible(true);
//布局文本框tf
gbc.fill=GridBagConstraints.BOTH;
addComponent(tf,gbl,gbc,1,2,2,1);
setVisible(true);
//布局标签l1
gbc.fill=GridBagConstraints.BOTH;
addComponent(l1,gbl,gbc,0,3,2,1);
setVisible(true);
//布局标签l2
gbc.fill=GridBagConstraints.BOTH;
addComponent(l2,gbl,gbc,1,3,2,1);
setVisible(true);

}
public static void main(String[] args) {
new GridBagLayoutDemo();
}
}
§卡片布局管理器(CardLayout): import javax.swing.*;
import java.awt.*;
public class CardLayoutDemo extends JFrame{
CardLayout cl;
JPanel p;
JButton b1,b2,b3,b4;
public CardLayoutDemo(){
super("卡片布局演示");
setSize(150,250);
cl=new CardLayout();
p=new JPanel();
p.setLayout(cl);
getContentPane().add(p);
b1=new JButton("我是第一张卡片");
b2=new JButton("我是第二张卡片");
b3=new JButton("我是第三张卡片");
b4=new JButton("我是第四张卡片");
p.add("b1",b1);
p.add("b2",b2);
p.add("b3",b3);
p.add("b4",b4);
setVisible(true);
while(true){
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
e.printStackTrace();
}
cl.next(p);
}

}
public static void main(String[] args) {
new CardLayoutDemo();
}
} §盒式布局管理器(BoxLayout): import java.awt.FlowLayout;
import java.awt.TextField;
import javax.swing.JButton;
import javax.swing.JLabel;
import javax.swing.Box;
import javax.swing.JFrame;

public class BoxLayoutDemo
{
public static void main(String args[])
{
JFrame frame=new JFrame("用户登录");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(300,200);
TextField password=new TextField(15);
password.setEchoChar('*');

Box left,right,top,bottom,base,basebox;

top=Box.createHorizontalBox();
top.add(new JLabel("用户登录"),JLabel.CENTER);

left=Box.createVerticalBox();
left.add(new JLabel("用户名:"));
left.add(Box.createVerticalStrut(8));
left.add(new JLabel("密码:"));

right=Box.createVerticalBox();
right.add(new TextField(10));
right.add(Box.createVerticalStrut(8));
right.add(password);

bottom=Box.createHorizontalBox();
bottom.add(new JButton("登录"));
bottom.add(Box.createVerticalStrut(10));
bottom.add