J2SE 布局

1.BorderLayout:

BorderLayout只管里容器中的5个组件的排列方式,这五个组件的位置分别位于 东、南、西、北、中 方向。

public class BorderLayoutDemo {
    public static void addComponentsToPane(Container pane) {
        JButton button = new JButton("[PAGE_START]");
        pane.add(button, BorderLayout.PAGE_START);
        button = new JButton("[CENTER]");
        button.setPreferredSize(new Dimension(500, 100));
        pane.add(button, BorderLayout.CENTER);
        button = new JButton("[LINE_START]");
        pane.add(button, BorderLayout.LINE_START);
        button = new JButton("Long Name Button [PAGE_END]");
        pane.add(button, BorderLayout.PAGE_END);
        button = new JButton("[LINE_END]");
        pane.add(button, BorderLayout.LINE_END);
    }

    private static void createAndShowGUI() {
        JFrame frame = new JFrame("BorderLayoutManage");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        addComponentsToPane(frame.getContentPane());
        frame.pack();
        frame.setVisible(true);
    }

    public static void main(String[] args) {
        javax.swing.SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                createAndShowGUI();
            }
        });
    }
}

2.BoxLayout

BoxLayout 对容器中的组件进行同一方向上的平均排列,纵向或者横向。

public class BoxLayoutDemo {
    public static void addComponentsToPane(Container pane) {
        JPanel xPanel = new JPanel();
        xPanel.setLayout(new BoxLayout(xPanel, BoxLayout.X_AXIS));
        addButtons(xPanel);
        JPanel yPanel = new JPanel();
        yPanel.setLayout(new BoxLayout(yPanel, BoxLayout.Y_AXIS));
        addButtons(yPanel);
        pane.add(yPanel, BorderLayout.PAGE_START);
        pane.add(xPanel, BorderLayout.PAGE_END);
    }

    private static void addAButton(String text, Container container) {
        JButton button = new JButton(text);
        button.setAlignmentX(Component.CENTER_ALIGNMENT);
        container.add(button);
    }

    private static void addButtons(Container container) {
        addAButton("Button 1", container);
        addAButton("Button 2", container);
        addAButton("Button 3", container);
        addAButton("Long Button 4", container);
        addAButton("Button 5", container);
    }

    private static void createAndShowGUI() {
        JFrame frame = new JFrame("BoxLayoutManage");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        addComponentsToPane(frame.getContentPane());
        frame.pack();
        frame.setVisible(true);
    }

    public static void main(String[] args) {
        javax.swing.SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                createAndShowGUI();
            }
        });
    }
}

3.CardLayout

 

posted @ 2017-03-27 15:02  牧 天  阅读(143)  评论(0)    收藏  举报