容器
每一个应用组件的应用程序都至少有一个顶层容器 ,应用程序必须创建一个顶层容器之后才能放置其他GUI容器或组件。
Swing提供了4种顶层容器。分别为JFrame、JApplet、JDialog和JWindow。其中,JFrame 和JDialog最为常用
package Demo01;
import java.awt.Container;
import java.awt.Label;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JDialog;
import javax.swing.JFrame;
public class DialogDemo01 extends JDialog{
public DialogDemo01(JFrame jframe) {
super(jframe,false);
this.setBounds(100,200,500,500);
Container container1=this.getContentPane();
container1.setLayout(null);
//container.add(new Label("大数据五班"));
JButton button1=new JButton("我是五班");
button1.setBounds(30,30,200,50);
container1.add(button1);
}
public static void main(String[]args) {
JFrame j=new JFrame();
j.setVisible(true);
j.setBounds(100,100,700,500);
j.setDefaultCloseOperation(EXIT_ON_CLOSE);
Container container=j.getContentPane();
container.setLayout(null);
JButton button=new JButton("我要登录");
button.setBounds(30,30,200,50);
button.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
DialogDemo01 s=new DialogDemo01(j);
s.setVisible(true);
System.out.println("我被点击了");
}
});
container.add(button);
}
}
FlowLayout布局管理器
package Demo03;
import java.awt.FlowLayout;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.WindowConstants;
public class TestFlowLayout2 {
public static void main(String[] args) {
JFrame j=new JFrame();
j.setVisible(true);
j.setBounds(100,100,700,500);
j.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
//j.setLayout(new FlowLayout());不传参数,默认居中
//j.setLayout(new FlowLayout(FlowLayout.RIGHT));
j.setLayout(new FlowLayout(FlowLayout.LEFT));
JButton button1=new JButton("button1");
JButton button2=new JButton("button2");
JButton button3=new JButton("button3");
JButton button4=new JButton("button4");
JButton button5=new JButton("button5");
JButton button6=new JButton("button6");
j.add(button1);
j.add(button2);
j.add(button3);
j.add(button4);
j.add(button5);
j.add(button6);
}
}
BordeLayout布局管理器
package Demo03;
import java.awt.BorderLayout;
import java.awt.FlowLayout;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.WindowConstants;
public class TestBorderLayout {
public static void main(String[] args) {
JFrame j=new JFrame();
j.setVisible(true);
j.setBounds(100,100,700,500);
j.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
JButton east=new JButton("east");
JButton west=new JButton("west");
JButton south=new JButton("south");
JButton north=new JButton("north");
JButton center=new JButton("canter");
j.add(east,BorderLayout.EAST);
j.add(west,BorderLayout.WEST);
j.add(south,BorderLayout.SOUTH);
j.add(north,BorderLayout.NORTH);
j.add(center,BorderLayout.CENTER);
}
}