關於setContentPane()和getContentPane()的應用

來源:互聯網
上載者:User

關於setContentPane()和getContentPane()的應用
我們可以在 JFrame 對象中添加 AWT 或者 Swing 組件。但是,雖然它有 add 方法,卻不能直接用於添加組件,否則會拋出異常——不信就試試。造成這個現象的原因只有一個解釋:JFrame 不是一個容器,它只是一個架構。那麼,應該怎麼添加組件呢?

  JFrame 有一個 Content Pane,視窗能顯示的所有組件都是添加在這個 Content Pane 中。JFrame 提供了兩個方法:getContentPane 和 setContentPane 就是用於擷取和設定其 Content Pane 的。

  對JFrame添加組件有兩種方式:
  1)用getContentPane()方法獲得JFrame的內容面板,再對其加入組件:frame.getContentPane().add(childComponent)
  2)建立一個Jpanel或JDesktopPane之類的中間容器,把組件添加到容器中,用setContentPane()方法把該容器置為JFrame的內容面板:
    JpanelcontentPane=newJpanel();
    ……//把其它組件添加到Jpanel中;
    frame.setContentPane(contentPane);
    //把contentPane對象設定成為frame的內容面板

聯繫我們

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