Search code examples
javaswingjbutton

Change JButton's click color?


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
        }

    });

Solution

  • 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
            }