I've created a JToggleButton and when it is selected the image is shown. It all works perfectly except the image isn't centered on the button. The top left corner of the image is on the center point of the button and then the image goes down and out towards the bottom right corner of the button.
JToggleButton LayoutButton = new JToggleButton();
LayoutButton.setIcon(new ImageIcon());
LayoutButton.setSelectedIcon(new ImageIcon("Image.png"));
Any ideas how I center the image?
Thanks
The problem is that your initial image does not match the dimensions of the selected image so, the selected image will appear in a different location, bottom right in this case.
You could create a placeholder for your initial 'unselected' image:
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) {
}
}
and replace your first zero-dimension image with:
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);