【Java GUI】架構視窗基礎

來源:互聯網
上載者:User

標籤:

視窗是GUI編程的基礎,小應用程式或圖形介面的應用程式的可視組件都放在視窗中,在GUI中,視窗是使用者螢幕的一部分,起著在螢幕中一個小螢幕的作用。有以下三種視窗:
①Applet視窗
②架構視窗(JFrame)
③一種無邊框視窗(JWindow)

用Swing中的JFrame類或它的子類建立的對象就是JFrame視窗。

JFrame類的主要構造方法:

JFrame();//建立無標題的視窗對象;JFrame(String s);//建立一個標題名是字串s的視窗對象。

JFrame類的其他常用方法:

setBounds(int x,int y,int width,int height);//參數x,y指定視窗出現在螢幕的位置;參數width,height指定視窗的寬度和高度。單位是像素。setSize(int width,int height);//設定視窗的大小,參數width和height指定視窗的寬度和高度,單位是像素。setBackground(Color c);//以參數 c設定視窗的背景顏色。setVisible(boolean b);//參數b設定視窗是可見或不可見。JFrame預設是不可見的。setTitle(String name);//以參數name設定視窗的名字。getTitle();//擷取視窗的名字。

Swing裡的容器都可以添加組件,除了JPanel及其子類(JApplet)之外,其他的Swing容器不允許把組件直接加入。其他容器添加組件有兩種方法:
一種是用getContentPane()方法獲得內容面板,再將組件加入。該代碼的意義是獲得容器的內容面板,並將按鈕button添加到這個內容面板中。
另一種是建立一個JPanel對象的中間容器,把組件添加到這個容器中,再用setContentPane()把這個容器置為內容面板。例如,代碼:
JPanel contentPane = new JPanel();
…
mw.setContentPane(contentPane);
以上代碼把contentPane置成內容面板。

//一個用JFrame類建立視窗的Java應用程式。視窗只有一個按鈕。import javax.swing.*;public class Test{    public static void main(String args[]){        JFrame mw = new JFrame(“我的第一個視窗”);        mw.setSize(250,200);        JButton button = new JButton(“我是一個按鈕”);        mw.getContentPane().add(button);        mw.setVisible(true);    }}

用Swing 編寫GUI程式時,通常不直接用JFrame建立視窗對象,而用JFrame派生的子類建立視窗對象,在子類中可以加入視窗的特定要求和特別的內容等。

//定義JFrame派生的子類MyWindowDemo建立JFrame視窗。類MyWindowDemo的構造方法有五個參數:視窗的標題名,加放視窗的組件,視窗的背景顏色以及視窗的高度和寬度。在主方法中,利用類MyWindowDemo建立兩個類似的視窗。import javax.swing.*;import java.awt.*;import java.awt.event.*;public class Test{    public static MyWindowDemo mw1;    public static MyWindowDemo mw2;    public static void main(String args[]){        JButton static butt1 = new JButton(“我是一個按鈕”);        String name1 = “我的第一個視窗”;        String name2 = “我的第二個視窗”;        mw1 = new MyWindowDemo(name1,butt1,Color.blue,350,450);        mw1.setVisible(true);        JButton butt2 = new JButton(“我是另一個按鈕”);        mw2 = new MyWindowDemo(name2,butt2,Color.magenta,300,400);        mw2.setVisible(true);    }}class MyWindowDemo extends JFrame{    public MyWindowDemo(String name,JButton button,Color c,int w,int h){        super();        setTitle(name);        setSize(w,h);        Container con = getContentPane();        con.add(button);        con.setBackground(c);    }}

【Java GUI】架構視窗基礎

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.