本文介绍了将其他JPanel添加到JPanel的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这里有个基本问题。

基本上我的代码是这样的:

Basically I have code like this:

public SuperPanel() {
    setLayout(new BorderLayout());
    add(panel1(), BorderLayout.NORTH);
    add(panel2(), BorderLayout.CENTER);
    add(panel3(), BorderLayout.SOUTH);
}

这一切都运作良好。问题是我还有另一部分要添加到中心。只是使用 add(newPanel(),BorderLayout.CENTER) 显然不起作用。但你可以在 JPanel 中添加 JPanel s,对吗?

And that all works well and good. The problem is that I have another part I wish to add to the center. Just using add(newPanel(), BorderLayout.CENTER) doesn't work, obviously. But you can add JPanels in JPanels, correct?

所以我做了以下更改:

public SuperPanel() {
    setLayout(new BorderLayout());
    add(panel1(), BorderLayout.NORTH);
    add(supersweetpanel(), BorderLayout.CENTER);
    add(panel3(), BorderLayout.SOUTH);
}

使用 supersweetpanel()是:

public JPanel supersweetpanel() {
    JPanel sswp = new JPanel();
    setLayout(new BorderLayout());
    add(panel2(), BorderLayout.NORTH);
    return sswp;
}

现在它会覆盖 panel1 !如果我把它设置为其他任何东西( CENTER SOUTH ,你有什么),前两个面板完全消失了。非常感谢帮助。

Now it overrides panel1! If I set it to anything else (CENTER, SOUTH, what have you), the first two panels disappear entirely. Help is much appreciated.

推荐答案

SuperPanel 可能是 JPanel ,对吗?您不小心将 panel2 添加到 SuperPanel ) ,而不是 sswp 。尝试:

SuperPanel is likely a subclass of JPanel, right? You are accidentally adding panel2 to this (the SuperPanel), not sswp. Try:

public JPanel supersweetpanel() {
        JPanel sswp = new JPanel();
        sswp.setLayout(new BorderLayout());
        sswp.add(panel2(), BorderLayout.NORTH);
        return sswp;
    }

这篇关于将其他JPanel添加到JPanel的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-05 16:18