Mouse over events with JButton
Solution 1
you can to use ButtonModel with ChangeListener
(by default) for JButtons JComponents there no reason to use
Mouse(Xxx)Listener
or itsMouseEvent
, all those events are implemented and correctly
Solution 2
As an alternative You can achieve this by registering MouseListener
to the JButton
and override mouseEntered()
,mouseExited()
, mousePressed()
and mouseReleased()
method.For Example:
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);
Related videos on Youtube
Van-Sama
Updated on August 30, 2022Comments
-
Van-Sama over 1 year
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:
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);
-
MadProgrammerTrue setting rollOverEnabled to true. You might also like to look at setRolloverSelectedIcon
-
-
Van-Sama about 11 yearsOh man I can't believe I didn't see that. See whenever I was doing the setRollOver, I was setting the image to the same exact image. Thanks man, number 1 really helped.