当我将鼠标悬停在它上面时如何更改JButton颜色,但是当我点击它时,即使我将鼠标悬停在其他地方,也会将其永久更改为其他颜色?

问题描述 投票:0回答:1

我想要一个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有意义,但我不知道如何得到我真正想要的结果。

java colors jbutton actionlistener mouselistener
1个回答
0
投票

听起来你希望按钮保持黄色,直到再次点击?

试试这个:

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"));
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.