简体   繁体   English

JButton的默认大小不能在GridBagLayout中更改

[英]JButton default size can't be changed in GridBagLayout

JButtons had the default size and I can't change it. JButtons具有默认大小,我无法更改。 I was try with setSize and it don't do anything. 我尝试使用setSize,它什么也没做。 When I click on some of JButtons picture will be set and the JButtons will get size of the picture. 当我单击某些JButton时,将设置图片,并且JButton将获得图片的大小。 I want to set size of JButton to be the same like the size of JButton when I click on it(JButton with picture) 我想将JButton的大小设置为与单击时的JButton的大小相同(带有图片的JButton)

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

 .........

在此处输入图片说明 在此处输入图片说明

Probably the simplest and most reliable solution is to use a blank image which is the same size as the others as the initial image for the button 可能最简单,最可靠的解决方案是使用空白图像,该空白图像的大小与按钮的初始图像大小相同

Very few layout managers allow you to directly suggest the size of a given component, in fact, the intention is to allow the component to tell the layout manager what it wants and then let the layout manager figure out if it can accomidate it. 很少有布局管理器允许您直接建议给定组件的大小,实际上,其目的是允许组件告诉布局管理器它想要什么,然后让布局管理器确定它是否可以容纳它。

For example... 例如...

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

}

In this example I've created my own blank image, you could do the same, but it's just as easy to load blank image, the concept is the same 在此示例中,我创建了自己的空白图像,您可以执行相同的操作,但是加载空白图像一样容易,概念是相同的

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM