2017年計算機(jī)二級考試java章節(jié)輔導(dǎo):容器組件

字號:


    8.1.1 JFrame
    JFrame是用來替代AWT包中Frame的,可以實(shí)現(xiàn)與Frame相同的功能,包括作為容器容納其他組件,顯示組件等。
    [例8-1]
    import javax.swing.*;
    import java.awt.*;
    class JFrameTest extends JFrame{
    private JButton button1 = new JButton("button1");
    private JButton button2 = new JButton("button2");
    public JFrameTest(String title){
    super(title);//設(shè)置標(biāo)題
    this.setBounds(50,50,200,150);
    //獲得與JFrame關(guān)聯(lián)的contentPane,contentPane默認(rèn)的布局管理器是BorderLayout
    Container contentPane = this.getContentPane();
    contentPane.setLayout(new FlowLayout(5));
    contentPane.add(button1);
    contentPane.add(button2);
    this.setVisible(true);
    //設(shè)置JFrame對關(guān)閉按鈕的處理方式
    this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    }
    }
    public class Test8_1 {
    public static void main(String[] args) {
    new JFrameTest("JFrame測試");
    }
    }
    程序運(yùn)行界面如下:
    圖8-2 例8-1運(yùn)行界面
    利用JFrame實(shí)現(xiàn)了與Frame相同的功能,但JFrame與Frame在使用上還是有很大區(qū)別的。
    (1)兩者都可以添加其他組件到窗口中,F(xiàn)rame直接使用add方法添加相應(yīng)的組件;JFrame則不能直接通過add方法添加組件,每個JFrame都有一個與之關(guān)聯(lián)的內(nèi)容面板(contentPane),只能針對這個contentPane添加相應(yīng)組件。
    (2)兩者都可以設(shè)置布局管理器,F(xiàn)rame直接使用setLayout即可設(shè)置;JFrame則需先得到其內(nèi)容面板,對其內(nèi)容面板設(shè)置布局管理器。
    (3)Frame要想關(guān)閉窗口需要編寫相應(yīng)的事件處理程序(見例7-12),而JFrame則不必編寫事件處理程序,只需調(diào)用方法setDefaultCloseOperation(int operation),通過設(shè)置operation的值來響應(yīng)用戶關(guān)閉窗體的操作,該方法的參數(shù)operation的值有以下三個。
    JFrame.DO_NOTHING_ON_CLOS:什么也不做
    JFrame.HIDE_ON_CLOSE:隱藏窗體,這是JFrame的默認(rèn)選項
    JFrame.EXIT_ON_CLOSE:關(guān)閉窗體,結(jié)束程序