Swing 程序用JFrame 對象實現了它們的窗口。JFrame 類是AWT Frame 類的一個子類。它還加入了一些Swing 所獨有的特性。與 Frame 的使用十分相似。唯一的區別在於,你不能將組件加入到JFrame中。你可以或者將組件加入到JFrame 的content pane(內容面板) 中,或者提供一個新的content pane(內容面板)。
面板與頂層容器的不同點:面板不能獨立存在,必須被添加到其他容器內部(面板可以嵌套)。
JFrame 有一個 Content Pane,窗口能顯示的所有組件都是添加在這個 Content Pane 中。JFrame 提供了兩個方法: getContentPane 和 setContentPane 就是用於獲取和設置其 Content Pane
的。
對JFrame添加組件有兩種方式:
1)用 getContentPane ()方法獲得JFrame的內容面板,再對其加入組件:frame. getContentPane ().add(childComponent)
2)建立一個Jpanel或JDesktopPane之類的中間容器,把組件添加到容器中,用setContentPane()方法把該容器置爲JFrame的內容面板:
JPanel contentPane = new JPanel();
……//把其它組件添加到Jpanel中;
frame.setContentPane(contentPane);
//把contentPane對象設置成爲frame的內容面板
實例程序:
import java.awt.*;
import javax.swing.*;
public class JFrameWithPanel {
public static void main(String[] args) {
JFrame frame = new JFrame("Frame With Panel");
Container contentPane = frame.getContentPane();
contentPane.setBackground(Color.CYAN); // 將JFrame實例背景設置爲藍綠色
JPanel panel = new JPanel(); // 創建一個JPanel的實例
panel.setBackground(Color.yellow); // 將JPanel的實例背景設置爲黃色
JButton button = new JButton("Press me");
panel.add(button); // 將JButton實例添加到JPanel中
contentPane.add(panel, BorderLayout.SOUTH); // 將JPanel實例添加到JFrame的南側
frame.setSize(300, 200);
frame.setVisible(true);
}
}
截圖: