按钮、文本域和其他的用户界面都会扩展Component类,组件可以放置在容器里(如:面板)中。由于Container类扩展自Component类,所以容器本身也可以放置在另一个容器中。
比如,Panel面板可以放置在顶级窗口Frame中,Panel可以实现自身嵌套,而Frame则不能。
下面是我为大家整理出的Component继承体系结构图,方便大家更好地学习Java GUI图形编程
下面我们来展示往Frame容器里添加Panel面板
public class Study1 {
public static void main(String[] args) {
Frame frame = new Frame("测试容器"); //创建frame窗口
frame.setVisible(true); //设置可见性
frame.setBackground(Color.gray); //设置背景颜色为灰色
frame.setBounds(300,300,400,300); //设置显示位置和大小
frame.setResizable(false);
frame.setLayout(null); //取消默认布局
frame.addWindowListener(new WindowAdapter() {
@Override
public void windowClosing(WindowEvent e) { //设置窗口关闭监听事件
System.exit(0);
}
});
Panel panel = new Panel(); //创建Panel对象
panel.setBounds(100,100,100,100); //设置面板的相对位置
panel.setBackground(Color.pink); //设置背景颜色为粉色
frame.add(panel); //往窗口中添加Panel面板
}
}
运行结果: