我已经创建了一个JToggleButton,当它被选中时,图像就会显示出来。这一切都很完美,除了图像不在按钮上居中。图像的左上角位于按钮的中心点,然后图像向下向按钮的右下角移动。
JToggleButton LayoutButton = new JToggleButton();
LayoutButton.setIcon(new ImageIcon());
LayoutButton.setSelectedIcon(new ImageIcon("Image.png"));
你知道我怎么把图像居中吗?
谢谢
发布于 2012-11-17 13:57:24
问题是,您的初始图像与所选图像的尺寸不匹配,因此,所选图像将出现在不同的位置,在这种情况下,右下角。
您可以为初始的“未选中”图像创建一个占位符:
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);
发布于 2012-11-17 13:43:58
您应该使用JToggleButton (实际上是AbstractButton的)的setHorizontalAlignment(...)
和setVerticalAlignment(...)
方法。将SwingConstants.CENTER
作为参数传入,使全部居中。
但请注意,horizontalAlignment和verticalAlignment属性的默认值已经是SwingConstants.CENTER。因此,如果这不起作用,请考虑发布一个小型的可编译和可运行的程序,该程序使用网络上随时可用的图像来向我们展示您的问题,sscce以及您当前按钮的外观图像。
https://stackoverflow.com/questions/13431037
复制相似问题