JFrame类中的getcontentpane方法

时间:2016-03-05 17:34:04

标签: java

getContentPaneJFrame class方法的用途是什么?我用Google搜索了,但我找不到合适的答案。

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");
            }

        });

    }
}

3 个答案:

答案 0 :(得分:0)

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

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

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

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

答案 1 :(得分:0)

  

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));

答案 2 :(得分:0)

Getvontentpane()将返回框架的内容窗格。 Contentpane就像是添加所有组件的地方。