java JSeparator 不会与 GridBagLayout 一起显示

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2425729/
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-10-29 21:05:16  来源:igfitidea点击:

JSeparator wont show with GridBagLayout

javauser-interfaceswinggridbaglayout

提问by Aly

I want to add a vertical JSeparator between two components using a GridBagLayout. The code I have is as follows:

我想使用 GridBagLayout 在两个组件之间添加一个垂直的 JSeparator。我的代码如下:

public MainWindowBody(){
    setLayout(new GridBagLayout());

    JPanel leftPanel = new InformationPanel();
    JPanel rightPanel = new GameSelectionPanel();

    JSeparator sep = new JSeparator(JSeparator.VERTICAL);
    GridBagConstraints gbc = new GridBagConstraints();

    gbc.gridx = 0;
    gbc.gridy = 0;
    gbc.anchor = GridBagConstraints.NORTH;

    add(leftPanel,gbc);

    gbc.gridx = 1;
    gbc.gridy = 0;
    gbc.fill = GridBagConstraints.VERTICAL;

    add(sep,gbc);

    gbc.gridx = 2;
    gbc.gridy = 0;
    gbc.fill = GridBagConstraints.NONE;

    add(rightPanel,gbc);
}

But the JSeperator doesn't show, any ideas?

但是 JSeperator 没有显示,有什么想法吗?

Thanks

谢谢

回答by Thomas

You could try to set the preferred width for the separator:

您可以尝试为分隔符设置首选宽度:

sep.setPreferredSize(new Dimension(5,1));

Then, make GridBagLayout use up all available height for the separator:

然后,让 GridBagLayout 用完分隔符的所有可用高度:

gbc.fill = GridBagConstraints.VERTICAL;
gbc.weighty = 1;

回答by Hyman

Taken from Sun'sguide for JSeparator:

摘自Sun 的指南JSeparator

In most implementations, a vertical separator has a preferred height of 0, and a horizontal separator has a preferred width of 0. This means a separator is not visible unless you either set its preferred size or put it in under the control of a layout manager such as BorderLayout or BoxLayout that stretches it to fill its available display area.

The vertical separator does have a bit of width (and the horizontal a bit of height), so you should see some space where the separator is. However, the actual dividing line isn't drawn unless the width and height are both non-zero.

在大多数实现中,垂直分隔符的首选高度为 0,水平分隔符的首选宽度为 0。这意味着分隔符不可见,除非您设置其首选大小或将其置于布局管理器的控制之下例如 BorderLayout 或 BoxLayout 将其拉伸以填充其可用显示区域。

垂直分隔符确实有一点宽度(而水平分隔符有一点高度),所以你应该看到分隔符所在的空间。但是,除非宽度和高度都非零,否则不会绘制实际的分界线。

Maybe you should set right constraints?

也许你应该设置正确的约束?