java - 当我将 GridBagLayout 添加到 JFrame 时,它​​不起作用

标签 java swing layout-manager gridbaglayout

我的 GridBagLayout 遇到一些问题。我创建了一个 JPanel(在本例中称为 mainPanel),其布局已设置为 GridBagLayout。我已经为每个 JButton 指定了约束,并将约束添加到每个按钮。现在,当我运行代码时,按钮始终彼此相邻,无论我在约束中指示的 gridx/gridy 值如何。此外,当我希望一个按钮出现在右上角、左上角和南边时,按钮始终位于 JFrame 的中心。

import javax.swing.*;
import java.awt.*;

public class test {
public static void main (String[] args) {
    myJFrame test = new myJFrame();
    }
}

class myJFrame extends JFrame {
   public myJFrame () {
      setSize(500,500);
      setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
      mainPanel myPanel = new mainPanel();
      add(myPanel);

     setVisible(true);
 }
}

class mainPanel extends JPanel {
    public mainPanel(){
       setLayout(new GridBagLayout());
       GridBagConstraints c = new GridBagConstraints();

        c.anchor =      GridBagConstraints.NORTHWEST;
        c.gridx =       1000;
        c.gridy=        1;
        add(new JButton("1"),c);

        c.anchor =      GridBagConstraints.NORTHEAST;
        c.gridx =       100;
        c.gridy=        1;
        add(new JButton("2"),c);

        c.anchor =      GridBagConstraints.SOUTH;
        c.gridx =       200;
        c.gridy=        1;
        add(new JButton("3"),c);
   }
}

This is what i get when i run the code

最佳答案

Now, when I run my code, the buttons are always next to each other, irrespective of the gridx/gridy value that I indicate in the constraints.

正确,您不能只指定随机单元格。每个单元格中必须有一个组件。

Furthermore, the buttons are always at the center of the JFrame,

是的,如果您不指定weightx/weighty约束,这是默认行为。

阅读 Swing 教程中关于 How to Use GridBagLayout 的部分有关约束和工作示例的更多信息。

为什么要随机选择 x 个位置,例如 100、200、1000?也许水平的 BoxLayout 会是更好的布局管理器。您可以添加组件,然后在它们之间添加空间:

panel.add( button1 );
panel.add( Box.createHorizonalStrut(100);
panel.add( button2 );
panel.add( Box.createHorizonalStrut(200);

或者可以使用 FlowLayout 并指定每个组件之间的“间隙”。

关于java - 当我将 GridBagLayout 添加到 JFrame 时,它​​不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36799170/

相关文章:

java - jsp中如何将对象类型转换为int

java - 在 Java 中的 JFrame/JPanel/JComponent 中添加 Web 浏览器

java - 如何删除 JGraphX 库中的顶点?

java - JTextPane 未在 GridBagConstraints 上水平填充

java - JScrollPane 中的 JTable

java - JPanel,调整大小的问题

java - 使用 CustomAuthenticationProvider 和 CustomPasswordEncoder 的 Spring-Boot

java - 无法发布通知 channel 空日志?

java - 数据未使用 SSL 在客户端和服务器之间传输

java - 在 NetBeans 中,如何将 jMenuBar 添加到 JPanel?