[英]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.