僅作為筆記 GUI繼承體系圖 Frame創建 public class Test{ public static void main(String[] args){ //新建Frame Frame frame = new Frame("This is frame title"); //設置可見性 fr ...
僅作為筆記
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
}
}