2012-11-17 87 views
2

我创建了一个JToggleButton,当它被选中时,图像显示。除了图像没有居中在按钮上之外,它都可以完美运行。图像的左上角位于按钮的中心点,然后图像向下并向着按钮的右下角。居中JToggleButton ImageIcon

JToggleButton LayoutButton = new JToggleButton(); 
LayoutButton.setIcon(new ImageIcon()); 
LayoutButton.setSelectedIcon(new ImageIcon("Image.png")); 

任何想法我如何居中形象?

感谢

回答

3

问题是,您的初始图像与所选图像的尺寸不匹配,因此,在这种情况下,所选图像将出现在不同的位置。

您可以为您最初的“未选择”图像占位符:

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

谢谢。我刚刚发现了这个!感谢您的解释修复 –

+0

没问题... :) – Reimeus

+0

干得好 - 当之无愧的1 +票! –

1

您应该使用JToggleButton中的setHorizontalAlignment(...)setVerticalAlignment(...)方法(的AbstractButton实际上)。以中间所有参数中的SwingConstants.CENTER作为参数。

虽然请注意horizo​​ntalAlignment和verticalAlignment属性的默认值已经是SwingConstants.CENTER。因此,如果这没有帮助,请考虑发布一个小型可编译和可运行的程序,该程序使用网络中的图像随时可用,向我们展示您的问题,sscce以及张贴您当前按钮的图像。

+0

感谢您SSCCE的建议。我没有没有选择的图像,所以当它添加图像选择它没有居中。如果我添加一个图像没有选择然后它的作品。必须与图像尺寸从未选中变为选中有关。 –