gpt4 book ai didi

java - 开始 GridBagLayout

转载 作者:行者123 更新时间:2023-12-02 12:32:23 26 4
gpt4 key购买 nike

我的问题是当我不乱用 ipadx 和 ipady 时。我的按钮粘在一起,但当我摆弄 ipadx 和 ipady 时,我发现第三个按钮将一个单元格移开。为什么以及如何解决这个困惑?代码:

public class Testagain extends JFrame {

private JPanel pan1;
private JPanel pan2;
private JPanel pan3;


private JButton btn1;
private JButton btn2;
private JButton btn3;


public Testagain()
{
super("Panel TEST GRID");
super.setSize(500, 500);

btn1 = new JButton(" 1");
pan1 = new JPanel(new GridBagLayout());
GridBagConstraints con1 = new GridBagConstraints();
con1.gridx = 0;
con1.gridy = 0;
con1.ipadx = 80;
con1.ipady = 60;
pan1.add(btn1,con1);

btn2 = new JButton("2");
pan2 = new JPanel(new GridBagLayout());
GridBagConstraints con2 = new GridBagConstraints();
con2.ipady = 60;
con2.ipadx = 0;
con2.gridx = 1;
con2.gridy = 0;
pan1.add(btn2,con2);



btn3 = new JButton("3");
pan3 = new JPanel(new GridBagLayout());
GridBagConstraints con3 = new GridBagConstraints();
con3.ipady = 60;
con3.ipadx = 0;
con3.gridx = 2;
con3.gridy = 0;


pan3.add(btn3,con3);


Container tain = super.getContentPane();
tain.setLayout(new GridBagLayout());

tain.add(pan1,con1);
tain.add(pan2,con2);
tain.add(pan3,con3);






super.setVisible(true);
super.setDefaultCloseOperation(EXIT_ON_CLOSE);
}

public static void main(String[] args)
{
new Testagain();
}

}

最佳答案

您将 btn1btn2 添加到 pan1 中,因此 pan2 被赋予了它自己的单元格...

btn1 = new JButton(" 1");
pan1 = new JPanel(new GridBagLayout());
//...
pan1.add(btn1,con1);

btn2 = new JButton("2");
pan2 = new JPanel(new GridBagLayout());
//...
pan1.add(btn2,con2);

所以,我稍微研究了一下你的代码,消除了一些困扰我的复杂性,并能够生成预期的输出

Expected Output

import java.awt.Container;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import javax.swing.JButton;
import javax.swing.JFrame;
import static javax.swing.JFrame.EXIT_ON_CLOSE;
import javax.swing.JPanel;

public class Testagain extends JFrame {

private JPanel pan1;
private JPanel pan2;
private JPanel pan3;

private JButton btn1;
private JButton btn2;
private JButton btn3;

public Testagain() {
super("Panel TEST GRID");
super.setSize(500, 500);

GridBagConstraints con1 = new GridBagConstraints();
btn1 = new JButton(" 1");
btn2 = new JButton("2");
btn3 = new JButton("3");

Container tain = super.getContentPane();
tain.setLayout(new GridBagLayout());

con1.gridx = 0;
con1.gridy = 0;
con1.ipadx = 80;
con1.ipady = 60;
tain.add(btn1, con1);
con1.ipadx = 0;
con1.gridx = 1;
con1.gridx = 60;
tain.add(btn2, con1);
con1.gridx = 2;
tain.add(btn3, con1);

super.setVisible(true);
super.setDefaultCloseOperation(EXIT_ON_CLOSE);
}

public static void main(String[] args) {
new Testagain();
}
}

我不知道为什么你使用中间面板来简单地添加一个按钮,但由于按钮和面板使用相同的约束,这对我来说似乎有些“奇怪”,但这可能是一个更大的快照,我不知道

关于java - 开始 GridBagLayout,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45259562/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com