IT评测·应用市场-qidao123.com
标题:
Java笔记(9) GUI->Frame和Panel
[打印本页]
作者:
怀念夏天
时间:
2023-4-5 18:23
标题:
Java笔记(9) GUI->Frame和Panel
仅作为笔记
GUI继承体系图
Frame创建
public class Test{
public static void main(String[] args){
//新建Frame
Frame frame = new Frame("This is frame title");
//设置可见性
frame.setVisible(true);
//设置窗口大小
frame.setSize(400,400);
//设置背景颜色
//1. 自行指定rgb,从而创建颜色
//2. 使用Color类的静态成员定义的预设方案
//frame.setBackground(new Color(125,125,125));//通过执行rgb值创建颜色方案
frame.setBackground(Color.lightgray);
//设置窗口弹出的位置
frame.setLocation(700,700);//指定窗口左上角坐标
//设置大小固定,不可拉伸
frame.setResizeable(false);
//监听关闭事件
frame.addwindowListener(new WindowAdapter(){
public void windowClosing(WindowEvent e){
System.exit(0);
}
});
}
}
复制代码
至此,一个Frame就定义完成了:
自定义Frame
在需要定义多个Frame的场景中,单独定义每个Frame的效率将会非常低,因此可以通过继承Frame的方式,自定义创建Frame的方法:
public class MyPanel extends Frame{
static int id = 0;//可能存在多个Frame,设置计数器
public MyFrame() throws Headless Exception{super();}//无参构造器
public MyFrame(String title) throws HeadlessException{};
public MyFrame(int x, int y, int w, int h, Color color){
super("Customized frame" + (++id));
setBackground(color);
setBounds(x,y,w,h);//≈setLocation()+setSize()
setResizable(false);
setVisible(true);
}
}
================================================
public class Test02{
public static void main(String[] args){
Frame frame1 = new MyFrame(300,300,200,200,Color.lightGray);
Frame frame2 = new MyFrame(500,300,200,200,Color.cyan);
}
}
复制代码
Panel
实际上,Frame往往仅作为容器存在,想要绘制的窗口内容一般在Panel中实现。
public class TestPanel{
public static void main(String[] args){
MyFrame myFrame = new MyFrame(300,300,500,500,Color.green);
myFrame.addWindowListener( new WindowAdapter(){
public void windowClosing(WindowEvent e){ System.exit(0); }
});
myFrame.setLayout(null); //设置Frame的布局
Panel panel = new Panel(); //添加Panel
panel.setBounds(50,50,200,200); //Panel设置坐标,其坐标是与其所在的Frame的相对坐标
panel.setBackground(Color.magenta); //设置Panel的背景
myFrame.add(panel); //将Panel添加到Frame
}
}
复制代码
免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作!
欢迎光临 IT评测·应用市场-qidao123.com (https://dis.qidao123.com/)
Powered by Discuz! X3.4