java - JPanel 中的 JButton 占用太多空间

标签 java swing jpanel jbutton gridbaglayout

我的一些按钮和面板有问题。我创建了一个带有 GridBagLayout 6x1 的 JPanel。

        GraphicPaintedPanel deck = new GraphicPaintedPanel();
        GridBagLayout gblDecks = new GridBagLayout();                                               
        gblDecks.columnWidths = new int[]{0, 0, 0, 0, 0, 0, 0};
        gblDecks.rowHeights = new int[]{0, 0};
        gblDecks.columnWeights = new double[]{0.15, 0.15, 0.15, 0.15, 0.15, 0.15, Double.MIN_VALUE};
        gblDecks.rowWeights = new double[]{1.0, Double.MIN_VALUE};
        deck.setLayout(gblDecks);

当我尝试向此面板添加按钮时,问题就出现了,因为它们根据按钮的数量占用空间,即使它们应该具有固定的大小。例如,如果我这样做

            for(int j=0; j<4; j++){
            JButton activate= new JButton("ACTIVATE LEADER CARD");
            GridBagConstraints gbcActivate = new GridBagConstraints();
            gbcActivate.gridx = j;
            gbcActivate.fill = GridBagConstraints.BOTH;
            deck.add(activate, gbcActivate);
            }

我创建了 4 个按钮,面板应该有 4 个按钮和 2 个“空白区域”。但它有 4 个按钮,占据了所有的空间。 enter image description here

如果我愿意

            for(int j=0; j<6; j++){
            JButton activate= new JButton("ACTIVATE LEADER CARD");
            GridBagConstraints gbcActivate = new GridBagConstraints();
            gbcActivate.gridx = j;
            gbcActivate.fill = GridBagConstraints.BOTH;
            deck.add(activate, gbcActivate);
            }

我得到的是这个enter image description here

尺寸不应该固定吗?谁能帮我吗?

最佳答案

gbcActivate.fill = GridBagConstraints.BOTH

如果我们转到tutorial它说:

fill
Used when the component's display area is larger than the component's requested size to determine whether and how to resize the component. Valid values (defined as GridBagConstraints constants) include NONE (the default), HORIZONTAL (make the component wide enough to fill its display area horizontally, but do not change its height), VERTICAL (make the component tall enough to fill its display area vertically, but do not change its width), and BOTH (make the component fill its display area entirely).

因此,它将独立于您为 columnWeights 等指定的内容来填充显示区域。尝试将其删除或更改为 GridBagConstraints.NONE

或者按照上面评论中的建议,使用另一个 layout managerFlowLayout

关于java - JPanel 中的 JButton 占用太多空间,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44930223/

相关文章:

java - 通过套接字发送javafx矩形/ Pane

java - 泛型上的通配符错误

java - 我的布局键盘上的空格键大小不会调整

java - 如何在同一面板上创建具有两个不同时间间隔的计时器/ Action 事件的多个动画组件?

java - 如何同时捕获两个异常作为一个单独的案例?

java - 用户连接时获取 native header

java - 仅对选定行使用 jTable.setRowHeight(selectedRow, 20)

java - 单击按钮后 GUI 卡住

java - 如何在基于 Java Swing 的 GUI 中隐藏/取消隐藏 SplitPane

java - 如何在 Java 中的 JFrame 上移动 JPanel?