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的內容面板:
1
2
3
4
|
…… //把其它組件添加到Jpanel中; frame.setContentPane(contentPane); //把contentPane對象設置成為frame的內容面板 |
實例程序:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
|
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 ); } } |
截圖:
總結
以上就是本文關于JFrame中添加和設置JPanel的方法實例解析的全部內容,希望對大家有所幫助。感興趣的朋友可以繼續參閱本站其他相關專題,如有不足之處,歡迎留言指出。感謝朋友們對本站的支持!
原文鏈接:http://blog.csdn.net/lyxaiclr/article/details/7366145/