我想要一个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"));
}
}