首页 > 解决方案 > 在鼠标悬停时更改 JButton 属性

问题描述

我正在用 swing 做一个计算器应用程序。我已经更改了 JButton 的背景颜色,但是当单击它时,它的颜色变为蓝色。我可以在鼠标悬停和单击时手动设置颜色吗?像 Windows 10 默认计算器?

标签: javaswingjbuttondesktop-application

解决方案


您需要首先使用鼠标侦听器检测鼠标在按钮上的移动。您可以使用它的实现版本,称为MouseAdapter

 button.addMouseMotionListener(new MouseAdapter()//To 
 detect mouse motion
  {
   @override
   public void mouseEntered(MouseEvent m)//called when mouse 
enters first time into the button
  {
    button.setBackground(Color.blue);
   }

     @override
     public void mouseClicked(MouseEvent m)//called when mouse is clicked[pressed and then released]
      {   
     button.setBackground(//whatever you want);
      }
     });

注意鼠标点击你可以改变你的动作监听器内的颜色


推荐阅读