0

I am trying to override the default background colour of the JButton while it is pressed; the background colour must stay as long as the button is still pressed.

I tried this code:

 button.addMouseListener(new MouseAdapter() {
    @Override
    public void mousePressed(MouseEvent evt) {
        button.setBackground(Color.BLUE); // applied after release!!
        System.out.println("pressed"); // applied on pressed - OK.
    }
});}

mousePressed here doesn't achieve my requirement!!

This line is never invoked: button.setBackground(Color.BLUE);. But this line is invoked: System.out.println("pressed");.

However this line button.setBackground(Color.BLUE); is invoked after releasing the button - Not while pressed!!!

How to achieve my requirement?

MadProgrammer
  • 343,457
  • 22
  • 230
  • 366
Saleh Feek
  • 2,048
  • 8
  • 34
  • 56

1 Answers1

0

Before your mouse-adapter part of code, make a Color object as:

final Color col = button.getBackground();

Then, in your mouse adapter, add this method:

public void mouseReleased(MouseEvent e)
{
    button.setBackground(col);
}

This makes your total code to :

final Color col = b.getBackground();

button.addMouseListener(new MouseAdapter() {

    public void mousePressed(MouseEvent e)
    {
        b.setBackground(Color.BLUE);
    }

    public void mouseReleased(MouseEvent e)
    {
        b.setBackground(g);
    }
});

So, when you press, the color changes to blue, and then when you release the mouse, it changes back to original. This works fine on my computer.

dryairship
  • 6,022
  • 4
  • 28
  • 54