繁体   English   中英

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

[英]Adding multiple JButtons moves other JButtons (Java)

我一直遇到的问题是,每当我向JPanel添加JButton时,我所使用的其他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。 有谁知道原因和/或解决方案?

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

我不知道你的意图是什么。 您只说它没有达到您的期望。 因此,我无法为您提供确切的解决方案。

在任何情况下,通过读取秋千教程部分开始如何使用GridBagLayout的使用工作的例子GridBagLayout

我看到两个问题:

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

  2. (500,....)的Insets值似乎很大。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM