无法在 GridBagLayout 中更改 JButton 默认大小

JButton default size can't be changed in GridBagLayout

JButtons 有默认大小,我无法更改它。我尝试使用 setSize 但它什么也没做。当我点击一些 JButtons 图片时,JButtons 将获得图片的大小。我想把JButton的大小设置成和我点击JButton时的大小一样(JButton with picture)

    btn=new JButton[9];
    j=0;

    for (i = 0; i <btn.length; i++) {
        btn[i] = new JButton("");
        btn[i].addActionListener(new ActionListener(){
            @Override
            public void actionPerformed(ActionEvent e) {
                if(j%2==0){
                    ((JButton) e.getSource()).setIcon(new ImageIcon("resources/X.png"));
                }else{
                    ((JButton) e.getSource()).setIcon(new ImageIcon("resources/O.png"));
                }
                ((JButton) e.getSource()).setEnabled(false);
                j++;
            }
        });

    }

GridBagConstraints gbc=new GridBagConstraints();

gbc.gridx=0;
gbc.gridy=0;
p2.add(btn[0],gbc);

gbc.gridx=1;
gbc.gridy=0;
p2.add(btn[1],gbc);

gbc.gridx=2;
gbc.gridy=0;
p2.add(btn[2],gbc);

 .........

可能最简单和最可靠的解决方案是使用与其他按钮大小相同的空白图像作为按钮的初始图像

很少有布局管理器允许您直接建议给定组件的大小,实际上,其目的是让组件告诉布局管理器它想要什么,然后让布局管理器确定它是否可以容纳它。

例如...

public class TestPane extends JPanel {

    public TestPane() {
        setLayout(new GridBagLayout());
        BufferedImage img = new BufferedImage(32, 32, BufferedImage.TYPE_INT_ARGB);
        Graphics2D g2d = img.createGraphics();
        g2d.setBackground(new Color(255, 255, 255, 0));
        g2d.clearRect(0, 0, 32, 32);
        g2d.dispose();
        GridBagConstraints gbc = new GridBagConstraints();
        for (int row = 0; row < 3; row++) {
            gbc.gridy = row;
            for (int col = 0; col < 3; col++) {
                gbc.gridx = col;
                add(new JButton(new ImageIcon(img)), gbc);
            }
        }
    }

    @Override
    public Dimension getPreferredSize() {
        return new Dimension(200, 200);
    }

}

在这个例子中我创建了自己的空白图像,你也可以这样做,但是加载空白图像同样容易,概念是一样的