I want to have a JButton on which when I hover over it, it should turn green and when the mouse exits it should go back to default but when I click on it should turn yellow and stay yellow whether or not I hover over it. Thanks.
I have already tried the mouselistener method.
public void mouseEntered(MouseEvent evt) {
bakery.setBackground(Color.GREEN);
}
public void mouseExited(MouseEvent evt){
bakery.setBackground(UIManager.getColor("control"));
}
public void mousePressed(MouseEvent evt){
bakery.setBackground(Color.YELLOW);
}
});
I expected that once I click it should stay yellow but it seems so when I exit the button area it goes back to default and when I hover again it gets green again. Which makes sense according to the mouselistener but I have no idea how to get the result I actually desire.
Sounds like you want the button to stay yellow, until clicked again?
Try this:
public void mouseEntered(MouseEvent e) {
if (bakery.getBackground() != Color.YELLOW) { // skip if already yellow
bakery.setBackground(Color.GREEN);
}
}
public void mouseExited(MouseEvent e) {
if (bakery.getBackground() != Color.YELLOW) { // skip if already yellow
bakery.setBackground(UIManager.getColor("control"));
}
}
public void mousePressed(MouseEvent e) {
if (bakery.getBackground() != Color.YELLOW) {
// The first click will set yellow
bakery.setBackground(Color.YELLOW);
} else {
// A second click clears the yellow.
bakery.setBackground(UIManager.getColor("control"));
}
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.