简体   繁体   English

将鼠标悬停在 Java Netbeans 中的 JButton 上

[英]Hovering on JButtons in Java Netbeans

Now I have multiple buttons on my JFrame, when the button is hovered, the button's color will be changed and after my cursor leaves the button, the button's color will change back to it's original color.现在我的 JFrame 上有多个按钮,当按钮悬停时,按钮的颜色会改变,当我的光标离开按钮后,按钮的颜色会变回原来的颜色。 As now I'm applying this code to all my buttons:现在我将这段代码应用到我所有的按钮上:

private void btn1MouseEntered(java.awt.event.MouseEvent evt) {                                       
        btn1.setBackground(new Color(236, 252, 250));
    }                                      

    private void btn1MouseExited(java.awt.event.MouseEvent evt) {                                      
        btn1.setBackground(new Color(241, 241, 241));
    }                 

Which makes me feel there's little bit of redundancy, is it possible to write a shorter code that the buttons will check itself whether it's hovered and will change color but change back to original color after unhovered?这让我觉得有一点冗余,是否可以编写一个较短的代码,按钮会检查自己是否悬停并更改颜色但在未悬停后变回原始颜色?

Which makes me feel there's little bit of redundancy这让我觉得有点多余

You can easily create a generic listener to be shared by all buttons:您可以轻松创建一个由所有按钮共享的通用侦听器:

MouseListener ml = new MouseAdapter()
{
    public void mouseEntered(java.awt.event.MouseEvent evt)
    {            
        Component c = evt.getComponent();                   
        c.setBackground(new Color(236, 252, 250));
    }                                      

    public void mouseExited(java.awt.event.MouseEvent evt)
    {                                      
        Component c = evt.getComponent();
        c.setBackground(new Color(241, 241, 241));
    }  
}

Then in your code you can add the listener to the button:然后在您的代码中,您可以将侦听器添加到按钮:

btn1.addMouseListener( ml );
btn2.addMouseListener( ml );

@camickr谢谢您,通过这种独特的方法对我的帮助很大。

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

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