Search code examples
javaswingjbuttonmouselistenerrollover

How to put Hover effect on jbutton?


I am trying to create a Java Desktop application where I am using two buttons. I want to add hover effect in those buttons. I want: When I click any button it should change its background color.

How can I achieve it?

Here is my code:

public class Party1Party2 extends JFrame
{
    JButton b1;
    JButton b2;
    Container pane;

    public Party1Party2()
    {
        getContentPane().setBackground(new java.awt.Color(255, 255, 255));

    b2.addActionListener(new ActionListener()
    {
        public void actionPerformed(ActionEvent ae)
        {
            JOptionPane.showMessageDialog(frame, "Welcome to allhabad High Court");
        }
    });

    b1.addActionListener(new ActionListener()
    {
        public void actionPerformed(ActionEvent ae)
        {
            JOptionPane.showMessageDialog(frame, "Welcome to allhabad High Court");

        }
    });
  }
}

Solution

  • You can use moused Entered and Exited the JButton, and do what ever you want.

    For Example:

    jButton1.addMouseListener(new java.awt.event.MouseAdapter() {
        public void mouseEntered(java.awt.event.MouseEvent evt) {
            jButton1.setBackground(Color.GREEN);
        }
    
        public void mouseExited(java.awt.event.MouseEvent evt) {
            jButton1.setBackground(UIManager.getColor("control"));
        }
    });