如何垂直对齐JFrame中的组件?

时间:2015-12-29 21:56:11

标签: java swing alignment components vertical-alignment

我尝试了多种解决方案,但没有任何东西适合我! 我想在框架的中心垂直对齐所有内容。

    window=new JFrame();
    window.setSize(520, 380);

    window.setTitle("Menu");
    window.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
    window.setLayout(new FlowLayout());   
    label=new JLabel("Settings",JLabel.CENTER);
    controlPanel= new JPanel();
    controlPanel.setLayout(new GridLayout(10,1));

    controlPanel.add(button1);//these are example components
    controlPanel.add(button2);
    controlPanel.add(button3);

    window.add(label);
    window.add(controlPanel);
    window.setVisible(true);

我希望将“设置”这个词作为标题,并在其下面放置我的组件。 我能够使用gridLayout而不是FlowLayout来执行此操作,但标题占据了屏幕的一半(我不想要那样)。 抱歉这样的基本问题,但我是java的新手:)

1 个答案:

答案 0 :(得分:1)

您可以使用GridBagLayout,例如......

GridBagLayout

import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
import javax.swing.border.EmptyBorder;

public class TestLayout {

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

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

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

    public class TestPane extends JPanel {

        public TestPane() {
            setBorder(new EmptyBorder(50, 50, 50, 50));
            setLayout(new GridBagLayout());
            GridBagConstraints gbc = new GridBagConstraints();
            gbc.gridwidth = GridBagConstraints.REMAINDER;
            gbc.fill = GridBagConstraints.HORIZONTAL;

            add(new JButton("Apples"), gbc);
            add(new JButton("Pears"), gbc);
            add(new JButton("Organges"), gbc);
            add(new JButton("Grapes"), gbc);
        }

    }

}

请记住,有了它的灵活性,就会带来复杂性。有关详细信息,请查看How to Use GridBagLayout