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);
.........
1 回答
可能最简单和最可靠的解决方案是使用与其他图像大小相同的空白图像作为按钮的初始图像
很少有布局管理器允许您直接建议给定组件的大小,实际上,目的是允许组件告诉布局管理器它想要什么,然后让布局管理器弄清楚它是否可以容纳它 .
例如...
在这个例子中我创建了自己的空白图像,你也可以这样做,但是加载空白图像同样容易,概念是一样的