简体   繁体   English

在鼠标悬停时更改 JButton 属性

[英]Change JButton properties on mouse over

I am doing a calculator app with swing.我正在用 swing 做一个计算器应用程序。 I have changed the background color of JButton but when clicked its color changes to a blueish color.我已经更改了 JButton 的背景颜色,但是当单击它时,它的颜色变为蓝色。 Can I set a color manually on mouse over and on click.我可以在鼠标悬停和单击时手动设置颜色吗? like the windows 10 default calculator?像 windows 10 默认计算器?

Try using this:尝试使用这个:

buttonName.setFocusPainted(false);

This will get rid of the default border when you click on a button.当您单击按钮时,这将摆脱默认边框。 To make the button do stuff ie change it's background you can implement the MouseListener interface for it, but I think the best thing for you would be to read about event handling in swing:) Here's a link要让按钮做一些事情,即改变它的背景,你可以为它实现 MouseListener 接口,但我认为对你来说最好的事情是阅读 swing 中的事件处理:) 这是一个链接

You need to first detect mouse motion over the button using an Mouse listener .You can use an implemented version of it called the MouseAdapter您需要首先使用鼠标侦听器检测鼠标在按钮上的移动。您可以使用它的实现版本,称为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);
      }
     });

Note for mouse clicks you can just change the color inside your action listener注意鼠标点击你可以改变你的动作监听器内的颜色

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM