![](/img/trans.png)
[英]Java Swing JButton change color slowly when hover on & leave
[英]How to change a JButton color when I hover over it but change it permanently to something else even if I hover afterwards when I click it?
我想要一个 JButton,当我将鼠标悬停在它上面时,它应该变成绿色,当鼠标退出时它应该回到默认状态,但是当我点击它时,它应该变成黄色并保持黄色,无论我是否悬停在它上面。 谢谢。
我已经尝试过 mouselistener 方法。
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);
}
});
我预计一旦我点击它应该保持黄色,但看起来当我退出按钮区域时它会恢复到默认状态,当我再次悬停时它会再次变为绿色。 根据鼠标侦听器,这是有道理的,但我不知道如何获得我真正想要的结果。
听起来您希望按钮保持黄色,直到再次单击?
尝试这个:
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"));
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.