Posted: November 17th, 2011 | Filed under: Java, Programmieren | Tags: Effekt, Hover, ImageIcon, Java, JButton, JButtonHoverable, MouseOver, Swing | No Comments »
Öfters verwende ich in meinen Programmen einen Button der sein Icon ändert sobald man mit der Maus über diesen fährt. Also ein JButton mit Hover-Effekt. Die folgende Klasse implementiert diese Funktionalität von Haus aus. Beim Konstruktoraufruf können zwei ImageIcons übergeben werden.
Hier die Klasse JButtonHoverable.java:
package de.roth.jsona.view.button;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import javax.swing.ImageIcon;
import javax.swing.JButton;
public class JButtonHoverable extends JButton{
private ImageIcon imageIconHovered;
private ImageIcon imageIcon;
private boolean hoverable;
public JButtonHoverable(ImageIcon imageIcon, ImageIcon imageIconHovered, String text){
super(imageIcon);
this.hoverable = true;
this.imageIconHovered = imageIconHovered;
this.imageIcon = imageIcon;
this.setText(text);
this.addHoverMouseListener();
}
public JButtonHoverable(ImageIcon imageIcon, ImageIcon imageIconHovered){
super(imageIcon);
this.hoverable = true;
this.imageIconHovered = imageIconHovered;
this.imageIcon = imageIcon;
this.addHoverMouseListener();
}
public ImageIcon getImageIconHovered() {
return imageIconHovered;
}
public ImageIcon getImageIcon() {
return imageIcon;
}
public void setHoverable(boolean hoverable){
this.hoverable = hoverable;
}
private void addHoverMouseListener(){
this.
addMouseListener(new MouseAdapter(){
public void mouseEntered(MouseEvent e) {
if(hoverable){
JButtonHoverable button = ((JButtonHoverable)e.getSource());
button.setIcon(button.getImageIconHovered());
}
}
public void mouseExited(MouseEvent e) {
JButtonHoverable button = ((JButtonHoverable)e.getSource());
button.setIcon(button.getImageIcon());
}
});
}
}
|
Und so wird die Klasse verwendet:
JButtonHoverable buttonHoverable = new JButtonHoverable(new ImageIcon(
getClass().getClassLoader().getResource(
"de/roth/icon/blau.png")), new ImageIcon(
getClass().getClassLoader().getResource(
"de/roth/icon/rot.png"))); |