Question

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

Was it helpful?

Solution

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);

OTHER TIPS

You should use the setHorizontalAlignment(...) and setVerticalAlignment(...) methods of JToggleButton (actually of AbstractButton). Pass SwingConstants.CENTER in as the parameter to center all.

Though note that the default value for the horizontalAlignment and verticalAlignment properties already are SwingConstants.CENTER. So if this doesn't help, consider posting a small compilable and runnable program that uses images off of the net readily available to us to show us your problem, an sscce as well as posting images of what your current buttons look like.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top