Swing流布局属性

时间:2012-12-13 22:04:21

标签: java swing layout-manager flowlayout

我一直在玩卡片布局演示:

http://docs.oracle.com/javase/tutorial/displayCode.html?code=http://docs.oracle.com/javase/tutorial/uiswing/examples/layout/CardLayoutDemoProject/src/layout/CardLayoutDemo.java

我想像这样构建一个gui,但是我正在努力使用流程布局,我发现其他属性可以根据需要帮助处理空间,但是我不能让它们使用这个例子。有人可以告诉我如何将以下属性应用于演示中的流程布局:

public FlowLayout(int alignment, int horizontalGap, int verticalGap)

任何帮助都会很棒。

1 个答案:

答案 0 :(得分:4)

有时候,你只需要试验......

enter image description here

public class TestFlow {

    public static void main(String[] args) {
        new TestFlow();
    }

    public TestFlow() {
        EventQueue.invokeLater(new Runnable() {
            @Override
            public void run() {
                try {
                    UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
                } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
                }

                JFrame frame = new JFrame();
                frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                frame.setLayout(new BorderLayout());
                frame.add(new TestPane());
                frame.pack();
                frame.setLocationRelativeTo(null);
                frame.setVisible(true);
            }
        });
    }

    public class TestPane extends JPanel {

        public TestPane() {
            setLayout(new GridLayout(0, 1));
            add(createPane(FlowLayout.LEFT, 5, 5));
            add(createPane(FlowLayout.CENTER, 15, 15));
            add(createPane(FlowLayout.RIGHT, 20, 20));
            add(createPane(FlowLayout.LEADING, 0, 0));
            add(createPane(FlowLayout.TRAILING, 5, 5));
        }

        protected JPanel createPane(int alignment, int hGap, int vGap) {

            JPanel panel = new JPanel(new FlowLayout(alignment, hGap, vGap));
            panel.setBorder(new LineBorder(Color.GRAY));
            panel.add(new JLabel("Left"));
            panel.add(new JLabel("Middle"));
            panel.add(new JLabel("Right"));

            return panel;

        }

    }

}