繁体   English   中英

JFrame类中的getcontentpane方法

[英]getcontentpane method in JFrame class

JFrame classgetContentPane方法有什么用? 我用谷歌搜索,但找不到合适的答案。

class MainFrame extends JFrame {

    public MainFrame(String title) {
        super(title);

        // Set layout manager
        setLayout(new BorderLayout());

        // Create Swing component
         JTextArea textArea = new JTextArea();
        JButton button = new JButton("Click me!");

        // Add Swing components to content pane
        Container c = getContentPane();

        c.add(textArea, BorderLayout.CENTER);
        c.add(button, BorderLayout.SOUTH);

        JButton button1 = new JButton("Click me again!");
        add(button1,BorderLayout.NORTH);
        button.addActionListener(new ActionListener() {

            @Override
            public void actionPerformed(ActionEvent e) {
                textArea.append("Hello\n");
            }

        });
        button1.addActionListener(new ActionListener() {

            @Override
            public void actionPerformed(ActionEvent e) {
                textArea.append("Hello\n");
            }

        });

    }
}

一个容器中有几层。 您可以将一层视为覆盖容器的透明薄膜。 在Java Swing中,用于保存对象的层称为内容窗格。 对象将添加到容器的内容窗格层。

getContentPane()方法检索内容窗格层,以便您可以向其添加对象。

内容窗格是由Java运行时环境创建的对象。 您不必知道内容窗格的名称即可使用它。

getContentPane()返回一个容纳对象的容器。 您可以在返回的容器上添加对象,而不是直接将对象添加到JFrame或JDialog。

JFrame类中的getcontentpane方法有什么用?

在这种情况下,没有。 由于Java 1.5 add已自动将组件添加到ContentPane因此

c.add(textArea, BorderLayout.CENTER);

可以写成

add(textArea, BorderLayout.CENTER); // can drop BorderLayout.CENTER obviously

类似于button1的处理方式

在某些情况下,获取ContentPane仍然有用,例如

setLayout(new BoxLayout(getContentPane(), BoxLayout.PAGE_AXIS));

Getvontentpane()将返回框架的contentpane。 Contentpane就像一个添加了所有组件的地方。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM