Luca
Luca

Reputation: 1874

Add component in a JPanel subclass

I want to create a JPanel subclass thats holds some JLabels. I started to write my code but I immediatly find a big problem. Component added to the JPanel subclass are not visible (or they are not added to JPanel I don' t kano). This is the code of the JPanel Subclass:

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);

    }

}

Upvotes: 1

Views: 1882

Answers (1)

Alix Martin
Alix Martin

Reputation: 332

You need to

  • put the JPanel in a top level container (like a JFrame)
  • call pack() on it so the LayoutManager finds room for your stuff

.

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);
    }
}

Upvotes: 1

Related Questions