简体   繁体   中英

How to change JButton background colour while it is pressed?

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?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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