【问题标题】:Add component in a JPanel subclass在 JPanel 子类中添加组件
【发布时间】:2012-09-21 12:52:49
【问题描述】:

我想创建一个包含一些 JLabel 的 JPanel 子类。我开始编写我的代码,但我立即发现了一个大问题。添加到 JPanel 子类的组件不可见(或者它们未添加到 JPanel 我不知道)。这是 JPanel 子类的代码:

public class ClientDetails extends JPanel
{

    private JLabel nameAndSurname = new JLabel ("Name & Surname");
    private JLabel company = new JLabel ("Company");

    private JPanel topPanel = new JPanel ();

    public ClientDetails ()
    {

        this.setBackground(Color.white);
        this.setLayout(new BorderLayout());

        topPanel.setLayout(new BoxLayout(topPanel, BoxLayout.Y_AXIS));
        topPanel.add(nameAndSurname);
        topPanel.add(company);

        this.add(topPanel,BorderLayout.PAGE_START);

    }

}

【问题讨论】:

  • 1) 不要扩展组件,只保留对它们的引用。 2) 为了尽快获得更好的帮助,请发帖SSCCE
  • 对不起,为什么不扩展呢?在我的情况下,最好有一个现成的组件来保存我的标签,以免代码复杂
  • 我要读这篇文章。谢谢。

标签: java swing inheritance jpanel composition


【解决方案1】:

你需要

  • 将 JPanel 放入顶级容器(如 JFrame)中
  • 调用 pack() 以便 LayoutManager 为你的东西找到空间

.

public  class Test extends JPanel {

    private JLabel nameAndSurname = new JLabel ("Name & Surname");
    private JLabel company = new JLabel ("Company");

    private JPanel topPanel = new JPanel ();
    JFrame frame;

    public Test()
    {
        this.setBackground(Color.white);
        this.setLayout(new BorderLayout());

        topPanel.setLayout(new BoxLayout(topPanel, BoxLayout.Y_AXIS));
        topPanel.add(nameAndSurname);
        topPanel.add(company);

        this.add(topPanel,BorderLayout.PAGE_START);

        frame = new JFrame("test");
        frame.add(this);
        frame.pack();
        frame.setVisible(true);
    }
}

【讨论】:

  • 问题是我在 JFrame 中使用了这个自定义 JPanel,它还有很多其他组件,所以我无法在我的 JPanel 子类中创建和打包它。我该如何解决?谢谢!
  • 在添加 JPanel 后是否要重新打包并重新绘制包含的 JFrame ?
  • JPanel 是随 NetBeans IDE 添加的,所以我认为 NetBeans 像所有其他组件一样做它
猜你喜欢
  • 2013-03-02
  • 1970-01-01
  • 1970-01-01
  • 2014-09-29
  • 2011-07-10
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-04-16
相关资源
最近更新 更多