I want to implement a button that does not show borders or anything else, except for an image that changes when you hover over it. Clicking on the image (showing the hover image) will execute some code.
I also would like to put all this in a separate class so I have a reusable component.
Extending a JButton delivers me the methods addActionListener() and so forth. But using the setAction() method removes the images that I set in the constructor. So it’s not watertight, as I cannot use an Action in combination with this class. And I certainly do not want to override method like setAction().
public class JHoverLabel extends JButton {
private final Icon normal;
private final Icon hovered;
public JHoverLabel (Icon normal, Icon hovered) {
this.normal = normal;
this.hovered = hovered;
setIcon(normal);
setFocusPainted(false);
setMargin(new Insets(0, 0, 0, 0));
setContentAreaFilled(false);
setBorderPainted(false);
setOpaque(false);
addMouseListener(new HoverListener());
}
private class HoverListener implements MouseListener {
@Override
public void mouseClicked(MouseEvent e) {}
@Override
public void mouseEntered(MouseEvent e) {
setIcon(hovered);
}
@Override
public void mouseExited(MouseEvent e) {
setIcon(normal);
}
@Override
public void mousePressed(MouseEvent e) {}
@Override
public void mouseReleased(MouseEvent e) {}
}
}
Extending a JLabel seems to do what a want in combination with a MouseListener, but I feel like using the wrong component here, because ‘click-on-me-to-do-something’ basically leads me to a JButton.
So what should I use? A JLabel or a JButton?
use implemented methods for JButton.setXxxIcon
instead of
MouseListeneryou can implements ButtonModel