我对GridLayout
有疑问,因为我知道我需要这个只是为了解决我的问题:我需要这个矩阵面板(在GridLayout
中制作)不可调整大小。例如,就像一个位于中间且无法调整大小的整个正方形。我做了很多研究工作,但找不到答案。
public class ButtonsMatrix extends JButton {
private int[][] fModel;
private int fX;
private int fY;
public ButtonsMatrix(int x, int y, int[][] model) {
fX = x;
fY = y;
fModel = model;
addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
fModel[fX][fY] = fModel[fX][fY] == 1 ? 0 : 1;
updateNameFromModel();
}
});
updateNameFromModel();
}
private void updateNameFromModel() {
setText(String.valueOf(fModel[fX][fY]));
}
public static void main(String[] args) {
int dim=10;
int matrix[][] = new int[10][10];
JFrame f = new JFrame("Window containing a matrix");
JPanel p = new JPanel();
JPanel extra = new JPanel(new FlowLayout());
extra.add(p);
p.setLayout(new GridLayout(dim, dim));
for (int r = 0; r < dim; r++){
for (int c = 0; c < dim; c++){
ButtonsMatrix button= new ButtonsMatrix(r, c, matrix);
p.add(button);
}
}
f.add(p);
f.pack();
f.setVisible(true);
}
}
最佳答案
将带有 GridLayout
的面板放入另一个带有 GridBagLayout
的面板中。
如果它是唯一的组件并且在添加时没有添加 GridBagConstraints
,则它将居中且其大小将保持不变,无论分配给具有网格包布局的面板的大小如何。
编辑
上面的代码将包含按钮网格布局的面板添加到 main 方法中定义的 extra
面板(该面板具有 FlowLayout
)。这还可以使按钮矩阵面板保持其首选尺寸。
代码的问题在于,它随后会忽略 extra
面板,并将 p
面板(带有按钮的网格布局)直接添加到 JFrame
与(默认)BorderLayout
。这样做会导致 p
面板被添加到边框布局的 CENTER
,这将拉伸(stretch)组件以填充可用的宽度和高度。
要解决这个问题,只需更改:
f.add(p);
致:
f.add(extra);
关于java - GridLayout 中的按钮,不可调整大小,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50543857/