Search code examples
javaswingjpanellayout-managerflowlayout

Initialize multiple JPanels using a Flow Layout (Homework)


I am trying to create a JFrame with two JPanels inserted inside using FlowLayout. I have the frame being initialized in a separate file, but here is what I have being called

public class FlowInFlow extends JFrame
{
public FlowInFlow() {

    setLayout(new FlowLayout());

    JPanel panel1 = new JPanel(new FlowLayout(FlowLayout.LEFT));
    panel1.setBackground(Color.RED);

    JPanel panel2 = new JPanel(new FlowLayout(FlowLayout.RIGHT));
    panel2.setBackground(Color.BLUE);   

}
}

Edit: When I run this I just get a blank box, when I need the two boxes side to side


Solution

  • As I've already stated, the default preferred size of a JPanel is 0x0...

    This means that when you add it to a layout like FlowLayout, the uses the preferred size, it will appear...well...it won't

    enter image description here

    public class TestFlowLayout {
    
        public static void main(String[] args) {
            new TestFlowLayout();
        }
    
        public TestFlowLayout() {
            EventQueue.invokeLater(new Runnable() {
                @Override
                public void run() {
                    JPanel master = new JPanel(new FlowLayout(FlowLayout.LEFT));
                    JPanel left = new JPanel();
                    left.setBackground(Color.RED);
                    left.add(new JLabel("Lefty"));
    
                    JPanel right = new JPanel();
                    right.setBackground(Color.BLUE);
                    right.add(new JLabel("Righty"));
    
                    master.add(left);
                    master.add(right);
    
                    JFrame frame = new JFrame();
                    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                    frame.setLayout(new BorderLayout());
                    frame.add(master);
                    frame.pack();
                    frame.setLocationRelativeTo(null);
                    frame.setVisible(true);
                }
            });
        }
    }