問題是,您的初始圖像與所選圖像的尺寸不匹配,因此,在這種情況下,所選圖像將出現在不同的位置。
您可以爲您最初的「未選擇」圖像佔位符:
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 +票! –