-1

I developed a virtual keyboard with JButtons. How do I change the color of the JButton while I am pressing it (with the mouse or keyboard) and revert back to the original color after leaving it ?

xav
  • 5,452
  • 7
  • 48
  • 57
  • `setBackground(color)` ?? – Salah Apr 08 '14 at 19:24
  • possible duplicate of [How to change a JButton color on mouse pressed?](http://stackoverflow.com/questions/14627223/how-to-change-a-jbutton-color-on-mouse-pressed) – demongolem Apr 08 '14 at 19:33
  • Either you can use a simple 'mouseListener' and 'setBackground(color)' when mouse is clicked or you can use different LOOK AND FEEL User Interfaces that gives such facility without really setting something. – Faran Yahya Apr 08 '14 at 19:35
  • closeparenthesis_0=new JButton(")
    0"); v add(closeparenthesis_0); Can someone show me an example of how to register after these commands?
    – user3512476 Apr 08 '14 at 19:50

1 Answers1

0

Keep the original background color of your button in the oldColor java.awt.Color variable. A MouseAdapter is a convenient way to avoid clutter.

You will just need to override mousePressed() and mouseReleased():

    ...
    oldColor = jButton1.getBackground();
    MouseListener mouseListener = new MouseAdapter() {
        @Override
        public void mousePressed(MouseEvent mouseEvent) {
            jButton1.setBackground(Color.green);
            doWhateverYouHaveToDo();
        }

        @Override
        public void mouseReleased(MouseEvent mouseEvent) {
            jButton1.setBackground(oldColor);
        }
    };
    jButton1.addMouseListener(mouseListener);
    ...
Costis Aivalis
  • 13,680
  • 3
  • 46
  • 47