我创建了一个 JToggleButton,选择它时会显示图像。除了图像没有以按钮为中心之外,一切都很完美。图像的左上角位于按钮的中心点,然后图像向下并向外朝向按钮的右下角。
JToggleButton LayoutButton = new JToggleButton();
LayoutButton.setIcon(new ImageIcon());
LayoutButton.setSelectedIcon(new ImageIcon("Image.png"));
有什么想法如何使图像居中吗?
谢谢
最佳答案
问题是您的初始图像与所选图像的尺寸不匹配,因此所选图像将显示在不同的位置,在本例中为右下角。
您可以为最初的“未选择”图像创建一个占位符:
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);
关于java - 将 JToggleButton ImageIcon 居中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13431037/