我正在做一个项目,需要一些自定义的swing组件。到目前为止,我已经用一系列图像制作了一个新的按钮(Java Metal外观与我的UI完全不匹配)。我在这个新组件上实现了
MouseListener
,这就是我的问题所在。我的小部件在悬停、点击等时改变图像,但我的MouseListener
会捕捉到鼠标进入整个GridLayout
容器而不是进入图像。因此,当图像大小为200*100,周围容器大小约为400*200时,即使在其空白区域上,mouseEntered
方法也会在进入该GridLayout
部分时触发。我怎样才能使它只在我悬停在图片上时触发?我已尝试设置大小、边界和其他属性,但都无济于事。
编辑: 这是我的问题演示。如您所见(有点难看出来,颜色非常相似),右下角的按钮只要进入GridlLayout
的那个区域就被突出显示了。我只希望它在我实际悬停在图像上方时被突出显示,而不是在GridLayout
部分。
我不会添加MouseListener
方法,因为它们只涉及切换显示的图像。
public customWidget()
{
this.setLayout(new FlowLayout());
try {
imageDef=ImageIO.read(new File("/home/x101/Desktop/buttonDef.png"));
imageClick=ImageIO.read(new File("/home/x101/Desktop/buttonClick.png"));
imageHover=ImageIO.read(new File("/home/x101/Desktop/buttonHover.png"));
current=imageDef;
} catch (IOException e)
{
e.printStackTrace();
}
this.addMouseListener(this);
}
protected void paintComponent(Graphics g)
{
super.paintComponents(g);
g.drawImage(current, 0, 0, current.getWidth(), current.getHeight(), null);
}
编辑:添加了代码部分