JFrame添加组件的两种方式
對JFrame添加組件有兩種方式:
1) 用getContentPane()方法獲得JFrame的內(nèi)容面板,再對其加入組件:frame.getContentPane().add(childCompontent)
常分開來寫
Container container=getContentPanel();(隱式的this.getContentPanel()) ;得到jframe的內(nèi)容面板
以后只要把容器加到container就可以了。
2) 建立一個JPanel或JDesktopPane之類的中間容器,把組件添加到容器中,用setContentPane()方法把該容器置為JFrame的內(nèi)容面板:
JPanel contentPane = new JPanel();
......//把其他組件添加到JPanel中
frame.setContentPane(contentPane);
//把contentPane對象設置成為frame的內(nèi)容面板
一般使用JFrame添加組件時,比如frame是JFrame的一個對象,我一般都是直接使用add()方法將組件加入,但是我看了很多例子,他們都是frame.getContentPane().add(),先得到內(nèi)容面板,然后再添加組件,這兩種方法的區(qū)別是什么,為什么后面那個好像用的多些呢?
網(wǎng)友回答:
An extended version ofjava.awt.Framethat adds support for the JFC/Swing component architecture. You can find task-oriented documentation about usingJFrameinThe Java Tutorial, in the sectionHow to Make Frames.
TheJFrameclass is slightly incompatible withFrame. Like all other JFC/Swing top-level containers, aJFramecontains aJRootPaneas its only child. Thecontent paneprovided by the root pane should, as a rule, contain all the non-menu components displayed by theJFrame. This is different from the AWTFramecase. As a convenianceaddand its variants,removeandsetLayouthave been overridden to forward to thecontentPaneas necessary. This means you can write:
frame.add(child);
JFrame類與Frame輕微不兼容。與其他所有 JFC/Swing 頂層容器一樣,JFrame包含一個JRootPane作為其唯一的子容器。根據(jù)規(guī)定,根窗格所提供的內(nèi)容窗格應該包含JFrame所顯示的所有非菜單組件。這不同于 AWTFrame。為了方便地使用add及其變體,已經(jīng)重寫了remove和setLayout,以在必要時將其轉發(fā)到contentPane。這意味著可以編寫:
frame.add(child);
import javax.swing.JFrame;
public class GameFrame {
public GameFrame()
{
JFrame frame=new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setTitle("3d tetris");
frame.setSize(500,300);
frame.setLocation(400,400);
frame.setVisible(true);
}
public static void main(String[] args)
{
GameFrame gameFrame=new GameFrame();
}
}
public class GameFrame extends JFrame{
public GameFrame()
{
super("3d tetris"); //設置標題,不要也可以
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setTitle("3d tetris");
setSize(500,300);
setLocation(400,400);
setVisible(true);
}
public static void main(String[] args)
{
GameFrame gameFrame=new GameFrame();
}
}
總結
以上是生活随笔為你收集整理的JFrame添加组件的两种方式的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: C# 彻底搞懂async/await
- 下一篇: Java 比较两个时间 时分秒 大小