JButtons 有默认大小,我无法更改它。我尝试使用 setSize 但它没有做任何事情。当我单击某些 JButtons 时,将设置图片,并且 JButtons 将获取图片的大小。我想将 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);
.........
最佳答案
可能最简单、最可靠的解决方案是使用与其他图像大小相同的空白图像作为按钮的初始图像
很少有布局管理器允许你直接建议给定组件的大小,事实上,目的是让组件告诉布局管理器它想要什么,然后让布局管理器弄清楚它是否可以容纳它.
例如...
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);
}
}
在此示例中,我创建了自己的空白图像,您也可以执行相同的操作,但加载空白图像同样容易,概念是相同的
关于java - GridBagLayout 中的 JButton 默认大小无法更改,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36663546/