我正在尝试使用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);

}
}


编辑:运行此程序时,我只得到一个空白框,当我需要两个框并排放置时

最佳答案

正如我已经说过的,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);
            }
        });
    }
}

09-10 09:07
查看更多