Java 布局管理器垂直居中

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/897924/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-11 20:47:49  来源:igfitidea点击:

Java layout manager vertical center

javaswinglayout

提问by Hamza Yerlikaya

I have panel that is using group layout to organize some label. I want to keep this panel center of the screen when re sized. If i put the panel inside a another panel using flow layout i can keep the labels centered horizontally but not vertically. Which layout manager will allow me to keep the panel centered in the middle of the screen?

我有使用组布局来组织一些标签的面板。我想在调整大小时保持这个面板在屏幕的中心。如果我使用流布局将面板放在另一个面板内,我可以将标签保持水平居中而不是垂直居中。哪个布局管理器可以让我将面板保持在屏幕中间居中?

I also tried border layout and placed it in the center but it resizes to the window size.

我还尝试了边框布局并将其放置在中心,但它会调整为窗口大小。

采纳答案by Michael Myers

Try using a GridBagLayoutand adding the panel with an empty GridBagConstrantsobject.
For example:

尝试使用 aGridBagLayout并添加带有空GridBagConstrants对象的面板。
例如:

public static void main(String[] args) {
    JFrame frame = new JFrame();
    frame.setLayout(new GridBagLayout());
    JPanel panel = new JPanel();
    panel.add(new JLabel("This is a label"));
    panel.setBorder(new LineBorder(Color.BLACK)); // make it easy to see
    frame.add(panel, new GridBagConstraints());
    frame.setSize(400, 400);
    frame.setLocationRelativeTo(null);
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.setVisible(true);
}

回答by Scott Stanchfield

First, I should mention, read my article on layouts: http://web.archive.org/web/20120420154931/http://java.sun.com/developer/onlineTraining/GUI/AWTLayoutMgr/. It's old but very helpful (unfortunately that article pre-dates BoxLayout. I have some slides when I gave that talk at JavaOne, which includes BoxLayout at http://javadude.com/articles/javaone)

首先,我应该提到,阅读我关于布局的文章:http://web.archive.org/web/20120420154931/http: //java.sun.com/developer/onlineTraining/GUI/AWTLayoutMgr/。它很旧但非常有用(不幸的是,那篇文章早于 BoxLayout。当我在 JavaOne 上进行演讲时,我有一些幻灯片,其中包括http://javadude.com/articles/javaone 上的BoxLayout )

Try BoxLayout:

尝试 BoxLayout:

Box verticalBox = Box.createVerticalBox();
verticalBox.add(Box.createVerticalGlue());
verticalBox.add(stuffToCenterVertically);
verticalBox.add(Box.createVerticalGlue());

and if you want to center that stuff, use a HorizontalBox as the stuffToCenterVertically:

如果您想将这些东西居中,请使用 Horizo​​ntalBox 作为 stuffToCenterVertically:

Box horizontalBox = Box.createHorizontalBox();
horizontalBox.add(Box.createHorizontalGlue());
horizontalBox.add(stuffToCenter);
horizontalBox.add(Box.createHorizontalGlue());

Way easier to "see" in the code than gridbag

在代码中比 gridbag 更容易“看到”

回答by BobMcGee

GroupLayout on the panel itself, with GroupLayout.Alignment.CENTER, for both vertical and horizontal, and setPreferredSize(new Dimension(yourChosenWidth,yourChosenHeight))to set the panel to not resize.

GroupLayout 在面板本身上,使用GroupLayout.Alignment.CENTER,用于垂直和水平,并将setPreferredSize(new Dimension(yourChosenWidth,yourChosenHeight))面板设置为不调整大小。

You might also do setMinimumSize and setMaximum size on the panel, just to be safe.

为了安全起见,您也可以在面板上执行 setMinimumSize 和 setMaximum size。

If you're feeling snazzy, you can just use one single GroupLayout for the whole thing, by carefully choosing parallel/sequential groups and grouping the labels appropriately.

如果您觉得很时髦,您可以通过仔细选择并行/顺序组并适当地对标签进行分组,将一个 GroupLayout 用于整个事情。

回答by adrian.tarau

You can build you own LayoutManager to center a single component(both axis or just one). Here is the one which does it on both axis, you can easily change it to have vertical or horizontal centering.

您可以构建自己的 LayoutManager 以将单个组件(两个轴或仅一个)居中。这是在两个轴上都做的一个,您可以轻松地将其更改为垂直或水平居中。

The current implementation layouts first visible child, you can change that too...

当前实现布局第一个可见的子项,您也可以更改它...

public class CentreLayout implements LayoutManager, java.io.Serializable {

public void addLayoutComponent(String name, Component comp) {
}

public void removeLayoutComponent(Component comp) {
}

public Dimension preferredLayoutSize(Container target) {
    return target.getPreferredSize();
}

public Dimension minimumLayoutSize(Container target) {
    return target.getMinimumSize();
}

public void layoutContainer(Container target) {
    synchronized (target.getTreeLock()) {
        Insets insets = target.getInsets();
        Dimension size = target.getSize();
        int w = size.width - (insets.left + insets.right);
        int h = size.height - (insets.top + insets.bottom);
        int count = target.getComponentCount();

        for (int i = 0; i < count; i++) {
            Component m = target.getComponent(i);
            if (m.isVisible()) {
                Dimension d = m.getPreferredSize();
                m.setBounds((w - d.width) / 2, (h - d.height) / 2, d.width, d.height);
                break;
            }
        }
    }
}

}