1

我想创建一个包含一些 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);

    }

}
4

1 回答 1

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);
    }
}
于 2012-09-21T13:14:16.003 回答