0

I've created some swing applications involving JButtons, and noticed whenever one is clicked, it turns white. Example here.

How would I change it so when, and only when, the button is clicked, it turns RED instead of the usual white, and when it is released, it goes back to its normal look? Is there a method for this?

Example code:

JButton b = new JButton("foo");
b.addMouseListener(new MouseAdapter(){


        @Override
        public void mousePressed(MouseEvent e) {
            //turn red
        }

        @Override
        public void mouseReleased(MouseEvent e) {
            //go back to original state
        }

    });
ruyili
  • 694
  • 10
  • 25

2 Answers2

0
JButton b = new JButton("foo");
b.addMouseListener(new MouseAdapter(){

    @Override
    public void mousePressed(MouseEvent e) {
        b.setBackground(Color.red);
    }

    @Override
    public void mouseReleased(MouseEvent e) {
        //go back to original state
    }

});

For more details look at this example

Community
  • 1
  • 1
0

change color of button text using setForeground method

like this

        @Override
        public void mousePressed(MouseEvent e) {
            b.setForeground(Color.red); // button text color
            // b.setBackground(Color.red); // button background color
        }

        @Override
        public void mouseReleased(MouseEvent e) {
            b.setForeground(Color.black); // button text color
        }
Rahmat Waisi
  • 1,293
  • 1
  • 15
  • 36