添加多个 JButton 会移动其他 JButton (Java)

Adding multiple JButtons moves other JButtons (Java)

我一直遇到的问题是,每当我将 JButton 添加到 JPanel 时,我拥有的任何其他 JButton 都会朝那个方向移动。

这是第一个代码:

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

public class Example {
  public static void main(String[] args) {
    // Create the frame and panel and the Grid Bag Constraints
    JFrame frame = new JFrame();
    JPanel panel = new JPanel(new GridBagLayout());
    GridBagConstraints c = new GridBagConstraints();
    // Create ONE JButton
    JButton button1 = new JButton("Button1");
    // Set the frame's properties
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.setSize(600, 600);
    frame.getContentPane().add(panel, BorderLayout.NORTH);
    frame.setVisible(true);
    // Set Basic Grid Bag Constraints settings.
    c.gridx = 0;
    c.gridy = 0;
    // Set the Insets
    c.insets = new Insets(0, 0, 0, 0);
    // Add the Grid Bag Constraints and button1 the panel
    panel.add(button1, c);
  }
}

似乎一切正常? 好吧,如果我们添加第二个按钮:

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

public class Example {
  public static void main(String[] args) {
    // Create the frame and panel and the Grid Bag Constraints
    JFrame frame = new JFrame();
    JPanel panel = new JPanel(new GridBagLayout());
    GridBagConstraints c = new GridBagConstraints();
    // Create TWO JButtons
    JButton button1 = new JButton("Button1");
    JButton button2 = new JButton("Button2");
    // Set the frame's properties
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.setSize(600, 600);
    frame.getContentPane().add(panel, BorderLayout.NORTH);
    frame.setVisible(true);
    // Set Basic Grid Bag Constraints settings.
    c.gridx = 0;
    c.gridy = 0;
    // Set the Insets
    c.insets = new Insets(0, 0, 0, 0);
    // Add the Grid Bag Constraints and button1 the panel
    panel.add(button1, c);
    // Set the Insets
    c.insets = new Insets(500, 0, 0, 0);
    // Add the Grid Bag Constraints and button2 the panel
    panel.add(button2, c);
  }
}

然后button1向下移动到button2。有谁知道为什么要 and/or 修复它?

编辑:我想问的是,如何在不移动其他按钮的情况下添加另一个按钮。

我不知道你的意图是什么。您只声明它没有按照您的预期进行。所以我不能给你一个确切的解决方案。

无论如何,请先阅读 Swing 教程中有关 How to Use GridBagLayout 的部分,了解使用 GridBagLayout 的工作示例。

我看到两个问题:

  1. 您永远不会更改 gridx/y 值。两个组件都添加到网格 (0, 0),这不是 GridBagLayout 应该如何工作。每个组件都需要添加到不同的单元格中。

  2. (500, ....)的Insets值好像很大。