Java getContentPane()
在 Java Swing 中,一个容器中有多个层,用于保存对象的层称为内容窗格。这个内容窗格是通过 getContentPane()
方法实现的。
对象被添加到特定容器的内容窗格层。本教程演示如何在 Java 中使用 getContentPane()
。
在 Java 中演示使用 GetContentPane()
内容窗格层由 getContentPane()
方法检索,我们可以在其中添加对象。内容窗格本身是由 Java 运行时环境创建的对象。
我们不需要知道任何内容窗格的名称即可使用它。当我们使用 getContentPane()
方法时,内容窗格对象在容器中被替换;在这个替换之后,我们可以对它应用任何方法。
让我们看一些例子:
package delftstack;
import javax.swing.JFrame;
import javax.swing.JLabel;
public class Get_Content_Pane {
public static void main(String[] args) {
JFrame demo_frame = new JFrame("GetContentPane");
final JLabel demo_label = new JLabel("Hello! This is delftstack..");
// Use getContentPane()
demo_frame.getContentPane().add(demo_label);
demo_frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
demo_frame.pack();
demo_frame.setVisible(true);
}
}
上面的代码显示了 getContentPane
的简单使用,它创建了一个带有 JLabel
的 JFrame
。
见输出:
让我们试试另一个例子:
package delftstack;
import java.awt.Container;
import javax.swing.*;
public class Get_Content_Pane {
public static void main(String[] args) {
JFrame Demo_Frame = new JFrame("GetContentPane");
Demo_Frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
Container Demo_Content_Pane = Demo_Frame.getContentPane();
Demo_Content_Pane.setLayout(null);
JButton button1 = new JButton("Button1");
JButton button2 = new JButton("Button2");
Demo_Content_Pane.add(button1);
Demo_Content_Pane.add(button2);
button1.setBounds(10, 10, 200, 30);
button2.setBounds(250, 10, 150, 40);
Demo_Frame.setBounds(0, 0, 500, 150);
Demo_Frame.setVisible(true);
}
}
上面的代码使用 getContentPane
创建了一个带有两个不同大小按钮的 JFrame
。
见输出:
声明:本站所有文章,如无特殊说明或标注,均为本站原创发布,任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站。本站所有源码与软件均为原作者提供,仅供学习和研究使用。如您对本站的相关版权有任何异议,或者认为侵犯了您的合法权益,请及时通知我们处理。