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