java 使用 JButton 将鼠标悬停在事件上
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/15403909/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Mouse over events with JButton
提问by Van-Sama
I'm trying to create a custom mouse over event on a JButton. The reason being that my JButton is currently an image, so I had to remove all the borders and animations and what not. so I did this:
我正在尝试在 JButton 上创建自定义鼠标悬停事件。原因是我的 JButton 目前是一个图像,所以我不得不删除所有的边框和动画,什么都没有。所以我这样做了:
btnSinglePlayer.setOpaque(false);
btnSinglePlayer.setContentAreaFilled(false);
btnSinglePlayer.setBorderPainted(false);
And that works perfect to only display the image, and the button does in fact work. I want to know if there's any pre-built methods perhaps that can do this, or how I would go about learning to do what I want.
这非常适合仅显示图像,并且按钮确实有效。我想知道是否有任何预先构建的方法可以做到这一点,或者我将如何学习做我想做的事。
More specifically, what I want the image to do when I mouse over is for it to get just a bit bigger.
更具体地说,当我将鼠标悬停在图像上时,我希望图像变大一点。
I have tried these so far, and did nothing:
到目前为止,我已经尝试过这些,但什么也没做:
btnSinglePlayer.setRolloverIcon(singlePlayerButton);
btnSinglePlayer.setPressedIcon(singlePlayerButton);
采纳答案by mKorbel
you can to use ButtonModel with ChangeListener
(by default) for JButtons JComponentsthere no reason to use
Mouse(Xxx)Listener
or itsMouseEvent
, all those events are implemented and correctly
您可以将ButtonModel 与 ChangeListener一起使用
(默认情况下)对于JButtons JComponents没有理由使用
Mouse(Xxx)Listener
或它的MouseEvent
,所有这些事件都被正确地实现
回答by Vishal K
As an alternative You can achieve this by registering MouseListener
to the JButton
and override mouseEntered()
,mouseExited()
, mousePressed()
and mouseReleased()
method.For Example:
作为替代可以通过注册实现这个MouseListener
到JButton
并覆盖mouseEntered()
,mouseExited()
,mousePressed()
和mouseReleased()
method.For实施例:
final ImageIcon icon1 = new ImageIcon("tray.gif");
final JButton button = new JButton(icon1);
final int width = icon1.getIconWidth();
final int height = icon1.getIconHeight();
button.addMouseListener(new MouseAdapter()
{
public void mouseEntered(MouseEvent evt)
{
icon1.setImage((icon1.getImage().getScaledInstance(width + 10, height,Image.SCALE_SMOOTH)));
//button.setIcon(icon1);
}
public void mouseExited(MouseEvent evt)
{
icon1.setImage((icon1.getImage().getScaledInstance(width , height,Image.SCALE_SMOOTH)));
}
public void mousePressed(MouseEvent evt)
{
icon1.setImage((icon1.getImage().getScaledInstance(width + 5, height,Image.SCALE_SMOOTH)));
}
public void mouseReleased(MouseEvent evt)
{
icon1.setImage((icon1.getImage().getScaledInstance(width + 10, height,Image.SCALE_SMOOTH)));
}
});
button.setOpaque(false);
button.setContentAreaFilled(false);
button.setBorderPainted(false);