我希望我的按钮在鼠标悬停在按钮上(悬停)时、按下按钮( Activity )时改变颜色,并保持这种状态直到用户选择其他选项。所以总是会选择其中之一。
我有三个按钮 - 圆形、方形和三角形。我的代码:
private static MouseListener ButtonMouseListener = new MouseAdapter () {
public void mouseEntered(MouseEvent evt) {
Component source = evt.getComponent();
source.setBackground(new Color(91, 90, 90));
}
public void mouseExited(MouseEvent evt) {
Component source = evt.getComponent();
source.setBackground(new Color(64, 64, 64));
}
public void mousePressed(MouseEvent evt) {
Component source = evt.getComponent();
source.setBackground(new Color(46, 46, 46));
}
};
所以我希望按钮在悬停在其上方时改变颜色(mouseEntered)
,并在有人停止悬停时再次将颜色更改为默认颜色(这就是为什么我有mouseExited
)。接下来的事情是我希望它们在被选择时改变颜色,所以 mousePressed
。问题是,当我将光标移到按钮之外时,由于 mouseExited
,它会变成另一种颜色,而我不希望这样。它必须保持“按下颜色”,直到用户选择三个按钮中的另一个。我不知道如何实现这一目标,我尝试了不同的选择,但没有一个能按照我想要的方式工作。
最佳答案
- 要更改条目颜色,您需要实现 Event->Mouse->
mouseEntered
。确保您在mouseExited
上实现它
当鼠标按下颜色变化时,您需要实现事件->操作。在
actionPerformed
中,您可以设置按钮颜色。例如:jButton7.setBackground(new Color(11, 118, 219)); jButton1.setBackground(new Color(15,44,123)); jButton8.setBackground(new Color(15,44,123)); jButton9.setBackground(new Color(15,44,123));
关于java - JButtons 鼠标事件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61206670/