首页 文章

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

提问于
浏览
0

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);

 .........

enter image description here

enter image description here

1 回答

  • 3

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

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

    例如...

    GridBagLayout

    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);
        }
    
    }
    

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

相关问题