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. 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 );