在JPanel子类中添加组件

时间:2012-09-21 12:52:49

标签: java swing inheritance jpanel composition

我想创建一个包含一些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 个答案:

答案 0 :(得分: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);
    }
}