使用Flow Layout(Homework)初始化多个JPanel

jro*_*sav 1 java swing jpanel layout-manager flowlayout

我正在尝试使用FlowLayout创建一个内部插入两个JPanel的JFrame.我有一个框架在一个单独的文件中初始化,但这是我所谓的

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

}
}
Run Code Online (Sandbox Code Playgroud)

编辑:当我运行这个时,我只得到一个空白框,当我需要两个盒子并排时

Mad*_*mer 5

正如我已经说过的,默认的首选大小JPanel是0x0 ......

这意味着当你将它添加到布局时FlowLayout,使用首选大小,它会出现......好吧......它不会

在此输入图像描述

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);
            }
        });
    }
}
Run Code Online (Sandbox Code Playgroud)