我的一些按钮和面板有问题。我创建了一个带有 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 个按钮,占据了所有的空间。
如果我愿意
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);
}
尺寸不应该固定吗?谁能帮我吗?
最佳答案
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 manager如FlowLayout
关于java - JPanel 中的 JButton 占用太多空间,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44930223/