问题是,您的初始图像与所选图像的尺寸不匹配,因此,在这种情况下,所选图像将出现在不同的位置。
您可以为您最初的“未选择”图像占位符:
public class PlaceHolderIcon implements Icon {
private final int width;
private final int height;
public PlaceHolderIcon(int width, int height) {
this.width = width;
this.height = height;
}
public int getIconHeight() {
return height;
}
public int getIconWidth() {
return width;
}
public void paintIcon(Component c, Graphics g, int x, int y) {
}
}
,并取代你的第一个零维图像:
ImageIcon selectedIcon = new ImageIcon("Image.png");
Image image = selectedIcon.getImage();
PlaceHolderIcon placeHolderIcon = new PlaceHolderIcon(image.getWidth(this), image.getHeight(this));
JToggleButton layoutButton = new JToggleButton();
layoutButton.setIcon(placeHolderIcon);
layoutButton.setFocusPainted(false);
layoutButton.setSelectedIcon(selectedIcon);
谢谢。我刚刚发现了这个!感谢您的解释修复 –
没问题... :) – Reimeus
干得好 - 当之无愧的1 +票! –