我在 GridBagLayout() 方面遇到问题并且列宽均匀。本质上,我使用 GridBagLayout lahyout 管理器向面板添加三个按钮。我希望(希望)按钮的宽度相同,并填充它们所在的单元格。但是,由于按钮的大小不同(取决于其中的文本),我最终会得到不同大小的按钮。下面是代码:
import java.awt.Dimension;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.util.ArrayList;
import java.util.List;
import javax.swing.*;
public class ShitHeadGUI extends JPanel {
public String[] s = new String[] {"Ace of Hearts", "2 of Diamonds", "3 of Clubs"};
//JPanel pile = new JPanel();
List<JPanel> hands = new ArrayList<JPanel>();
GridBagConstraints cons = new GridBagConstraints();
JFrame frame = new JFrame("Shithead");
public ShitHeadGUI() {
this.setLayout(new BoxLayout(this, BoxLayout.Y_AXIS));
this.setPreferredSize(new Dimension(300,300));
cons.gridx = 0;
cons.gridy = 0;
cons.weightx = 1;
cons.fill = GridBagConstraints.HORIZONTAL;
for (int i = 0; i < 2; i++) {
hands.add(new JPanel());
hands.get(i).setLayout(new GridBagLayout());
this.add(hands.get(i));
cons.gridy++;
}
frame.setVisible(true);
frame.add(this);
frame.pack();
addCards(null);
}
public void addCards(Hand h) {
List<JButton> btnCard = new ArrayList<JButton>();
for (int i = 0; i < 3; i++) {//h.size(); i++) {
cons.gridx = i;
//btnCard.add(new JButton(h.getCard(i).toString()));
btnCard.add(new JButton(s[i]));
hands.get(0).add(btnCard.get(i), cons);
}
}
}
“红心 A”与“方 block 2”的尺寸略有不同,而“梅花 3”则明显较小。我希望它们都大小相同。任何帮助将不胜感激,谢谢!!
最佳答案
有一个小技巧...将所有组件的首选大小设置为一些愚蠢的小尺寸,例如:
setPreferredSize(new Dimension(2, 2));
并添加以下内容:
c.fill = GridBagConstraints.BOTH;
c.weightx = 1.0; // fill all available space horizontally
c.weighty = 1.0; // fill all available space vertically
关于java - 无法使用 GridBagLayout 布局管理器获得等宽列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41923709/