第十二章 GUI编程
1. 提纲
2. AWT包
3. Component和Container
4. Frame类
代码1:
import java.awt.*;
public class TestFrame {
public static void main(String[] args) {
Frame f = new Frame("My First Frame"); //给Frame起一个名字
f.setSize(170,100); //设置初始大小
f.setBackground(Color.blue); //设置背景颜色
f.setVisible(true); //显示Frame
}
}
代码2:
import java.awt.*;
public class TestMultiFrame {
public static void main (String[] args) {
MyFrame f1 = new MyFrame(100,100,200,200,Color.BLUE);
MyFrame f2 = new MyFrame(300,100,200,200,Color.YELLOW);
MyFrame f3 = new MyFrame(100,300,200,200,Color.GREEN);
MyFrame f4 = new MyFrame(300,300,200,200,Color.MAGENTA);
}
}
class MyFrame extends Frame {
static int id = 0;
MyFrame (int x,int y,int w,int h,Color color) {
super("MyFrame" + (++id));
setBackground(color);
setLayout(null); //不设置其页面布局管理器
setBounds(x,y,w,h);
setVisible(true);
}
}
5. Panel类
代码1:
import java.awt.*;
public class TestPanel {
public static void main (String[] args) {
Frame f = new Frame("Java Frame with Panel");
Panel p = new Panel(null); //初始化一个Panel,并且不设置其布局管理器
f.setLayout(null); //设置Frame的布局管理器为空
f.setBounds(300,300,500,500);
f.setBackground(new Color(0,0,102)); //计算机三原色:红绿蓝;占一个字节
p.setBounds(50,50,400,400);
p.setBackground(new Color(204,204,255));
p.setBackground(new Color(204,204,255));
f.add(p); //Panel不能独立显示,必须处于其他顶级容器中
f.setVisible(true);
}
}
代码2:
import java.awt.*;
public class TestMultiPanel {
public static void main (String[] args) {
new MyFrame("MyFrameWithPanel",300,300,400,300);
}
}
class MyFrame extends Frame {
private Panel p1,p2,p3,p4;
MyFrame (String s,int x,int y,int w,int h) {
super(s);
setLayout(null);
p1 = new Panel(null);
p2 = new Panel(null);
p3 = new Panel(null);
p4 = new Panel(null);
p1.setBounds(0,0,w/2,h/2);
p2.setBounds(0,h/2,w/2,h/2);
p3.setBounds(w/2,0,w/2,h/2);
p4.setBounds(w/2,h/2,w/2,h/2);
p1.setBackground(Color.RED);
p2.setBackground(Color.GREEN);
p3.setBackground(Color.YELLOW);
p4.setBackground(Color.BLUE);
add(p1);add(p2);add(p3);add(p4);
setBounds(x,y,w,h);
setVisible(true);
}
}
代码3:
import java.awt.*;
public class CenterPanel {
public static void main (String[] args) {
new MyFrame(300,300,400,300,Color.BLUE);
}
}
class MyFrame extends Frame {
private Panel p;
MyFrame(int x,int y,int w,int h,Color c) {
super("Frame with Panel");
setLayout(null);
setBounds(x,y,w,h);
setBackground(c);
p = new Panel(null);
p.setBounds(w/4,h/4,w/2,h/2);
p.setBackground(Color.YELLOW);
add(p);
setVisible(true);
}
}
6. 布局管理器
- FlowLayout布局管理器
代码1:
import java.awt.*;
public class TestFlowLayout {
public static void main (String[] args) {
Frame f = new Frame("FlowLayout"