1

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

}
}

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

4

2 回答 2

5

正如我已经说过的,a 的默认首选大小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);
            }
        });
    }
}
于 2012-11-01T03:43:52.483 回答
4

除了更改外部布局的建议外,这些组件从未被添加到任何东西中(因此永远不会可见)。

网格中的红/蓝流

import java.awt.*;
import javax.swing.*;

public class FlowInGrid extends JFrame  {

    public FlowInGrid() {

        setLayout(new GridLayout(1,0));

        JPanel panel1 = new JPanel(new FlowLayout(FlowLayout.LEFT));
        panel1.setBackground(Color.RED);
        // ADD Them to something!
        add(panel1);

        JPanel panel2 = new JPanel(new FlowLayout(FlowLayout.RIGHT));
        panel2.setBackground(Color.BLUE);   
        // ADD Them to something!
        add(panel2);
    }

    public static void main(String[] args) throws Exception {
        Runnable r = new Runnable() {
            @Override
            public void run() {
                JFrame f = new FlowInGrid();
                f.setSize(300,100);
                f.setVisible(true);
            }
        };
        SwingUtilities.invokeLater(r);
    }
}
于 2012-11-01T03:41:51.283 回答