阅读编辑2以了解我实际需要的内容
我目前正在尝试使用在Photoshop中创建的带有alpha参数的图像创建一些自定义JButtons。
到目前为止,通过覆盖paint()方法来绘制图像已经起作用,因为按钮显示了正确的图像。然而,我想通过使其形状(可点击区域)与图像上可见像素相同来改进它(现在如果绘制按钮的边框,它是一个正方形)。
有没有简单的方法可以做到这一点,或者我必须解析图像并找到透明像素以制作自定义边框?
我需要重写哪些方法才能使它按照我想要的方式工作?
另外,我以后还会有另一个问题:是否最好使用某种算法来更改图像的颜色,以使人们在单击它时看起来像是被单击了,还是我最好创建第二个图像,并在按钮处于活动状态时绘制该图像?
编辑:我刚刚在其他问题上读到,我应该重新定义paintComponent()而不是paint(),我想知道为什么,因为重新定义paint()也可以正常工作?
编辑2:我改变了一切,以确保我的JButtons使用带有图标的默认构造函数创建。我想要做的是获取注册单击的X和Y位置,并抓取该位置处的图标像素,并检查其alpha通道是否为0(如果是,则不执行任何操作,否则执行它应该执行的操作)。
问题在于,alpha通道总是返回255(透明像素上的蓝色、红色和绿色为238)。在其他像素上,一切都返回应该返回的值。
这里是一个重现我的问题的示例(如果您愿意,请尝试使用另一张图像):
public class TestAlphaPixels extends JFrame
{
private final File FILECLOSEBUTTON = new File("img\\boutonrondX.png"); //My round button with transparent corners
private JButton closeButton = new JButton(); //Creating it empty to be able to place it and resize the image after the button size is known
public TestAlphaPixels() throws IOException
{
setLayout(null);
setSize(150, 150);
closeButton.setSize(100, 100);
closeButton.setContentAreaFilled(false);
closeButton.setBorderPainted(false);
add(closeButton);
closeButton.addMouseListener(new MouseListener()
{
public void mouseClicked(MouseEvent e)
{
}
public void mousePressed(MouseEvent e)
{
}
public void mouseReleased(MouseEvent e)
{
System.out.println("Alpha value of pixel (" + e.getX() + ", " + e.getY() + ") is: " + clickAlphaValue(closeButton.getIcon(), e.getX(), e.getY()));
}
public void mouseEntered(MouseEvent e)
{
}
public void mouseExited(MouseEvent e)
{
}
});
Image imgCloseButton = ImageIO.read(FILECLOSEBUTTON);
//Resize the image to fit the button
Image newImg = imgCloseButton.getScaledInstance((int)closeButton.getSize().getWidth(), (int)closeButton.getSize().getHeight(), java.awt.Image.SCALE_SMOOTH);
closeButton.setIcon(new ImageIcon(newImg));
}
private int clickAlphaValue(Icon icon, int posX, int posY)
{
int width = icon.getIconWidth();
int height = icon.getIconHeight();
BufferedImage tempImage = (BufferedImage)createImage(width, height);
Graphics2D g = tempImage.createGraphics();
icon.paintIcon(null, g, 0, 0);
g.dispose();
int alpha = (tempImage.getRGB(posX, posY) >> 24) & 0x000000FF;
return alpha;
}
public static void main(String[] args)
{
try
{
TestAlphaPixels testAlphaPixels = new TestAlphaPixels();
testAlphaPixels.setVisible(true);
testAlphaPixels.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
catch(IOException ioe)
{
ioe.printStackTrace();
}
}
}
这只是一个猜测,但是当我的图像被转换为图标时,它是否失去了Alpha属性,因此没有返回正确的值?无论如何,如果有人能真正帮助我并告诉我应该改变什么来获得正确的值,我将不胜感激。
我猜这是因为当我尝试使用原始图像时,Alpha通道的值是正确的,但是我实际上不能使用那个BufferedImage,因为我调整了它的大小,所以我实际上获得的是具有原始大小的图像的通道值...
JLabel
并将图像设置为其图标呢? - Moonbeam