adding multiple jPanels to jFrame

dave picture dave · Jun 13, 2011 · Viewed 68.8k times · Source

I want to add two jPanels to a JFrame side by side. the two boxes are jpanels and the outer box is a jframe enter image description here

I have these lines of code. I have one class called seatinPanel that extends JPanel and inside this class I have a constructor and one method called utilityButtons that return a JPanel object. I want the utilityButtons JPanel to be on the right side. the code I have here only displays the utillityButtons JPanel when it runs.

public guiCreator()
    {
        setTitle("Passenger Seats");
        //setSize(500, 600);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        Container contentPane = getContentPane();

        seatingPanel seatingPanel1 = new seatingPanel();//need to declare it here separately so we can add the utilityButtons
        contentPane.add(seatingPanel1); //adding the seats
        contentPane.add(seatingPanel1.utilityButtons());//adding the utility buttons

        pack();//Causes this Window to be sized to fit the preferred size and layouts of its subcomponents
        setVisible(true);  
    }

Answer

Heisenbug picture Heisenbug · Jun 13, 2011

The most flexible LayoutManager I would recommend is BoxLayout.

You can do the following :

JPanel container = new JPanel();
container.setLayout(new BoxLayout(container, BoxLayout.X_AXIS));

JPanel panel1 = new JPanel();
JPanel panel2 = new JPanel();

//panel1.set[Preferred/Maximum/Minimum]Size()

container.add(panel1);
container.add(panel2);

then add container to object to your frame component.