微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

如何将容器添加到框架?

如何解决如何将容器添加到框架?

我正在尝试制作一个扫雷艇,它有不同的空间来放置我们可以点击的笑脸图标和我们必须点击才能播放的按钮。

public final class testFrame extends JFrame implements MouseListener,ActionListener {

private JFrame screen = null;
private JPanel composite = new JPanel();
public testFrame() {
    screen = new JFrame();
    screen.setDefaultCloSEOperation(JFrame.EXIT_ON_CLOSE);
    screen.setVisible(true);
    screen.setResizable(true);
    composite.setLayout(new BorderLayout());
    //this button is not showing also
    JButton button = new JButton("Text goes here");
    composite.add(button);

    Container cp = screen.getContentPane();           // JFrame's content-pane
    cp.setLayout(new GridLayout(5,5,2,2)); // in 10x10 GridLayout
    //codes to add buttons
 }

所以在这里我尝试将容器 cp 添加到屏幕上。但是开了 two screen

对不起,如果这看起来是小事,但我对这个 Java GUI 真的很陌生,所以请帮助我。

编辑: 我删除了扩展 JFrame 并使用屏幕代替。它有点工作,但我似乎无法将容器 cp 放在面板上。要求是我必须使用容器cp。所以我无法改变。谢谢

public final class TestFrame implements MouseListener,ActionListener {
 private JFrame screen = null;
 private JPanel composite = new JPanel();
 private JPanel topPanel = new JPanel();
 public TestFrame() {
    screen = new JFrame("TestFrame");
    screen.setDefaultCloSEOperation(JFrame.EXIT_ON_CLOSE);
    screen.setVisible(true);
    topPanel.setLayout(new BorderLayout());
    //composite.setLayout(new BorderLayout());

    //button in topPanel
    JButton button = new JButton("Text goes here");
    topPanel.add(button,BorderLayout.PAGE_START);
    //Content Pane
    Container cp = screen.getContentPane();// JFrame's content-pane
    cp.setLayout(new GridLayout(5,2)); // in 10x10 GridLayout

    //composite.add(cp,BorderLayout.CENTER);
    screen.add(topPanel);
    // screen.add(composite);
 }

现在看起来像 this

解决方法

有几件事。

  1. 您正在扩展 JFrame 并将其用作同一类的属性,因此您可以使用 this 而不是 screen 或删除 extends JFrame,因为它是多余的并且不需要
  2. 回答您的问题。 JFrame 包含一个名为 ContentPane 的面板,该面板是您将面板添加到的(您已经正确地进行了布局)。所以解决方案是:
cp.add(composite);
,

您有太多的 JFrame、扩展 JFrame 的 testFrame 类(并且应该将其重命名为 TestFrame 以符合 Java 命名约定)和屏幕变量。只使用一个。

您可以并且应该嵌套 JPanel 以实现您想要的结果。例如,如果你想要一个网格和一些控制按钮,创建一个 JPanel,给它一个 BorderLayout,把你的网格 JPanel 放在 BorderLayout.CENTER 位置,一个带有控件 JButtons 的 JPanel 放在不同的位置,比如 {{1 }}

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。