从Java Swing的左上角开始GridBagLayout

Emi*_*mir 12 java swing gridbaglayout

我是Java Swing的新手,我一直在努力从左上角开始GridBagLayout,这样c.gridx = 0 c.gridy = 0会将我的对象放在左上角.

如果你能在这一点之后告诉我需要做什么,我将不胜感激:

    JPanel panel = new JPanel(new GridBagLayout());
    frame.add(panel);
    GridBagConstraints c = new GridBagConstraints();
Run Code Online (Sandbox Code Playgroud)

我知道我必须使用NORTHWEST或FIRST_LINE_START常量,但我不知道如何.我尝试这样做'但它没有意识到常数.

    frame.getContentPane().add(panel, BorderLayout.NORTHWEST);
Run Code Online (Sandbox Code Playgroud)

谢谢你的帮助.

cam*_*ckr 15

阅读Swing教程中有关如何使用GridBagLayout的部分.关于"weightx,weighty"的部分说明:

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


Mar*_*ers 12

你需要使用你的GridBagConstraints' anchor财产.这应该为你做:

frame.setLayout(new GridBagLayout());
GridBagConstraints gbc = new GridBagConstraints();
gbc.anchor = GridBagConstraints.NORTHWEST;
frame.add(panel, gbc);
Run Code Online (Sandbox Code Playgroud)

我不保证你不必设置约束对象的其他属性来获得你想要的布局.特别是,你可能需要设置widthx,并widthy1使面板占用了所有给它的可用空间.


mrd*_*abd 6

一个快速而简单的方法:

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

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

    bg.add(new JLabel(" "), gbc);  // blank JLabel
Run Code Online (Sandbox Code Playgroud)


pee*_*nut 5

对于那些使用IDE(例如NetBeans)的人,我终于找到了一个很好的技巧:如果你想将组件添加到顶部并使用他们的首选大小:添加另一个空的面板,其中weighty = 1.0.从自动生成的代码(NetBeans)复制:

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


Alp*_*Man 5

有一个解决方法。您可以将 GridBagLayout 面板放入具有 BorderLayout.NORTH 的 BorderLayout 面板中。然后 GridBagLayout 面板中的组件将从顶部位置开始。

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);
}
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述