如何在我将鼠标悬停在 JButton 上时更改它的颜色,但即使我在单击它之后悬停它也将其永久更改为其他颜色?
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);
}
});
我原以为一旦我点击它应该保持黄色,但似乎当我退出按钮区域时它会恢复默认状态,当我再次悬停时它会再次变成绿色。根据 mouselistener 的说法,这是有道理的,但我不知道如何获得我真正想要的结果。
听起来你想让按钮保持黄色,直到再次点击?
试试这个:
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"));
}
}
我想要一个 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);
}
});
我原以为一旦我点击它应该保持黄色,但似乎当我退出按钮区域时它会恢复默认状态,当我再次悬停时它会再次变成绿色。根据 mouselistener 的说法,这是有道理的,但我不知道如何获得我真正想要的结果。
听起来你想让按钮保持黄色,直到再次点击?
试试这个:
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"));
}
}