从Java Swing的左上角开始GridBagLayout

问题描述 投票:12回答:6

[我是Java Swing的新手,我一直在努力从左上角启动GridBagLayout,以便c.gridx = 0 c.gridy = 0将我的对象放在左上角。

如果能在此之后告诉我需要做些什么,我会很感激:

    JPanel panel = new JPanel(new GridBagLayout());
    frame.add(panel);
    GridBagConstraints c = new GridBagConstraints();

我知道我必须使用NORTHWEST或FIRST_LINE_START常量,但我不知道如何。我试图以此方式进行操作”,但它没有意识到常量。

    frame.getContentPane().add(panel, BorderLayout.NORTHWEST);

感谢您的帮助。

java swing gridbaglayout
6个回答
11
投票

您需要使用GridBagConstraints'anchor属性。这应该为您做到:

frame.setLayout(new GridBagLayout());
GridBagConstraints gbc = new GridBagConstraints();
gbc.anchor = GridBagConstraints.NORTHWEST;
frame.add(panel, gbc);

我不保证您不必设置约束对象的其他属性即可获得所需的布局。特别是,您可能需要将weightxweighty设置为1,以便面板占用分配给它的所有可用空间。


15
投票

请阅读Swing教程中有关How to Use GridBagLayout的部分。 “ weightx,weighty”的第二部分指出:

除非您为weightx或weighty指定至少一个非零值,否则所有组件都将聚集在其容器的中央。


5
投票

对于那些使用IDE(例如NetBeans)的人,我终于找到了一个不错的窍门:如果要在顶部添加组件并使用其首选大小:添加另一个权重= 1.0的空白面板。从自动生成的代码(NetBeans)复制:

gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 2;
gridBagConstraints.weighty = 1.0;
jPanelOptions.add(jPanelFiller, gridBagConstraints);

4
投票

一种快速简单的方法:

在页面末尾添加一个空白的JLabel:

    // your code goes here
    gbc.weightx = 1;
    gbc.weighty = 1;

    bg.add(new JLabel(" "), gbc);  // blank JLabel

2
投票

有一种解决方法。您可以使用BorderLayout.NORTH将GridBagLayout面板放置在BorderLayout面板中。然后,GridBagLayout面板中的Component将从顶部开始。

static void test4(){
    JFrame frame = new JFrame("Test");
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.setSize(480, 360);

    JPanel borderLayoutPanel=new JPanel(new BorderLayout());
    JPanel gridBagLayoutPanel = new JPanel(new GridBagLayout());
    borderLayoutPanel.add(gridBagLayoutPanel, BorderLayout.NORTH);
    frame.add(borderLayoutPanel);

    JButton testButton=new JButton("test button");
    GridBagConstraints c = new GridBagConstraints();
    c.gridx=0;
    c.gridy=0;
    gridBagLayoutPanel.add(testButton, c);

    frame.setVisible(true);
}

enter image description here


1
投票

如果您希望网格一直延伸到顶部,只需将所有权重设置为0,直到最后一项,将其设置为大于0的任何数字,它将有效地将其余按钮推到顶部。

不要忘记也增加按钮的网格值。

否则它将居中。(如果您不使用c.fill = GridBagConstraints.HORIZONTAL属性,则可以使用gridx和weightx值进行相同操作。)

© www.soinside.com 2019 - 2024. All rights reserved.