java - 无法使用 GridBagLayout 布局管理器获得等宽列

标签 java gridbaglayout

我在 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/

相关文章:

java - 为什么我的长整数会稍微改变一点?

java - gridbaglayout 的第二行滚动出容器

java - 设置布局时出现问题

java - GridBagConstraints问题-向左移动且大小不一样

java - Swing:GridBagLayout动态复选框位置

java - 更新 Tomcat Lib 文件夹

java - 有没有办法在 iText7 中的文本之前保留空格?

java - 如何通过eclipse使用Web服务客户端generetad

java - 调用一个从scala代码接受 `<? super T>`类型参数的java方法?

java - 你如何在java中使用gridbaglayout?