【Java GUI】Java架構視窗基礎

來源:互聯網
上載者:User

標籤:

視窗是GUI變成的基礎,小應用程式或圖形介面的應用程式的可視組件都放在視窗中。在GUI中,視窗是使用者螢幕的一部分,起著在螢幕中一個小螢幕的作用。有下面三種視窗:
①Applet視窗: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);setBackground(Color c);setVisible(boolean b);//視窗是否可見pack();用緊湊方式顯示視窗。setTitle(String name);//設定視窗的名字getTitle();//擷取視窗的名字setResiable(boolean m);//設定當前視窗是否可調整大小

Swing裡的容器都可以添加組件,除了JPanel及其子類(JApplet)之外,其他的Swing容器不允許把組件直接加入。其他容器添加組件有兩種方法:
①用getContentPane()方法獲得內容面板,然後將組件加入。
②建立一個JPanel對象的中間容器,把組件添加到這個容器中,再用setContentPane()把這個容器置為內容面板。

//一個用JFrame類建立視窗的Java應用程式,視窗只有一個按鈕import java.swing.*;public class Example {    public static void main(String []args) {        JFrame mw = new JFrame("My first window");        mw.setSize(250,200);        JButton button = new JButton("My first button");        mw.getContentPane().add(button);        mw.setVisible(true);    }}

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

//定義JFrame派生的子類MyWindowDemo建立JFrame視窗。類MyWindowDemo的構造方法有五個參數:標題名,放入的組件,視窗的背景顏色以及視窗的高度和寬度。在主方法中,利用類MyWindowDemo建立兩個類似的視窗。import java.awt.*;import javax.swing.*;public class Test {    public static MyWindowDemo mw1;    public static MyWindowDemo mw2;    public static void main(String []args) {        JButton butt1 = new JButton("Button");        String name1 = "My first window";        String name2 = "My second window";        mw1 = new MyWindowDemo(name1,butt1,Color.blue,350,450);        mw1.setVisible(true);        JButton butt2 = new JButton("another Button");        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】Java架構視窗基礎

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.