14

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

        }
    });
  }
}
Paul Samsotha
  • 205,037
  • 37
  • 486
  • 720
user3456343
  • 252
  • 3
  • 7
  • 21
  • @peeskillet can u tell me how can i make jbutton as a rounded rectangel – user3456343 Mar 25 '14 at 15:36
  • Honestly, I would just look into changing the look and feel. I don't like messing with component appearance. See [this post](http://stackoverflow.com/a/22166047/2587435) and see [Modifying the Look and Feel](http://docs.oracle.com/javase/tutorial/uiswing/lookandfeel/index.html) – Paul Samsotha Mar 25 '14 at 15:42
  • all attempts about mouse listener are wrong, with side effect, to ignore those answers – mKorbel Mar 25 '14 at 21:19
  • @mKorbel -- Could you please point me to some more learning on why (or when) it's not good to use mouse listeners, and what is the preferred alternative approach? (not necessarily in the context of OP's question) Thanks.Fifteen minutes of Googling didn't yield anything for me. – fountainhead Nov 11 '19 at 09:19

4 Answers4

24

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"));
    }
});
Salah
  • 8,567
  • 3
  • 26
  • 43
  • 2
    answer is wrong, all mouse events are implemented in JButtons API and correctly use them instead of mouse listener – mKorbel Mar 25 '14 at 21:21
  • 13
    Oh eeeeasy, I think you're trying to say that there is a better way to do this, But it is not a WRONG answer, at least to me because i did it many times, and please be more modern in your comments!!! – Salah Mar 26 '14 at 07:09
  • 2
    Ok, then please be be clear in the next time that you meant to edit my answer or to notice me that there is a better way by using something else, that was not clear in your previous comment when you said `ignore those answers` and `answer is wrong`, and thanks for your hints, ill update my answer. – Salah Mar 26 '14 at 09:24
  • 4
    This discussion if for nothing, especially because of the lacking reference to the "better" idea. I found it here: http://stackoverflow.com/questions/16733708/changing-value-of-boolean-when-mouse-cursor-hovers-over-a-jbutton/16733866#16733866 – Mariana Jul 29 '16 at 06:34
  • what "control means"? – Volazh Aug 27 '16 at 22:02
4

I once wrote a custom JButton which used to change its transparency level when the mouse was hovered over it through animation. Here's the code for that button:

import javax.swing.*;
import java.awt.*;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;

public class HoverButton extends JButton
{
  float alpha = 0.5f;

  public HoverButton(String text)
  {
    super(text);
    setFocusPainted(false);
    setBorderPainted(false);
    setContentAreaFilled(false);
    addMouseListener(new ML());
  }

  public float getAlpha()
  {
    return alpha;
  }

  public void setAlpha(float alpha)
  {
    this.alpha = alpha;
    repaint();
  }

  public void paintComponent(java.awt.Graphics g)
  {
    java.awt.Graphics2D g2 = (java.awt.Graphics2D) g;
    g2.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER, alpha));
    super.paintComponent(g2);
  }

  public class ML extends MouseAdapter
  {
    public void mouseExited(MouseEvent me)
    {
      new Thread(new Runnable()
      {
        public void run()
        {
          for (float i = 1f; i >= .5f; i -= .03f)
          {
            setAlpha(i);
            try
            {
              Thread.sleep(10);
            }
            catch (Exception e)
            {
            }
          }
        }
      }).start();
    }

    public void mouseEntered(MouseEvent me)
    {
      new Thread(new Runnable()
      {
        public void run()
        {
          for (float i = .5f; i <= 1f; i += .03f)
          {
            setAlpha(i);
            try
            {
              Thread.sleep(10);
            }
            catch (Exception e)
            {
            }
          }
        }
      }).start();
    }

    public void mousePressed(MouseEvent me)
    {
      new Thread(new Runnable()
      {
        public void run()
        {
          for (float i = 1f; i >= 0.6f; i -= .1f)
          {
            setAlpha(i);
            try
            {
              Thread.sleep(1);
            }
            catch (Exception e)
            {
            }
          }
        }
      }).start();
    }
  }
}

And here's a quick demonstration of the HoverButton:

import javax.swing.*;
import java.awt.*;

public class Demonstration
{
  public Demonstration()
  {
    JFrame frame = new JFrame("Hover Button Demonstration");
    frame.setLayout(new GridBagLayout());
    frame.add(new HoverButton("Hover Button!!"));

    frame.pack();
    frame.setLocationRelativeTo(null);
    frame.setVisible(true);
  }

  public static void main(String args[])
  {
    SwingUtilities.invokeLater(new Runnable()
    {
      @Override
      public void run()
      {
        new Demonstration();
      }
    });
  }
}

Good thing is that you can tweak the code to change the background color of the button as well, and that too, in an animated way.

Aman Agnihotri
  • 2,973
  • 1
  • 18
  • 22
1

Wow. Old question, I know, but...

To change the background, use:

b1.setBackground(new java.awt.Color(r, g, b));

in the actionListener.

For a rollover effect, you can use:

b1.setRolloverEnabled(true);

but you will need to supply icons for your buttons to flip between.

Otherwise, for other hover effects, you do need to use a mouseListener.

0

@Salah's answer didn't work for me at first, but it did after I disabled my button's rollover effect using

button1.setRolloverEnabled(false);

The rollover effect was automatically setting my button's hover color, which was overriding the color I set in mouseEntered().

Jasperan
  • 2,154
  • 1
  • 16
  • 40