I developed a virtual keyboard with JButton
s.
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 ?
Asked
Active
Viewed 171 times
-1

xav
- 5,452
- 7
- 48
- 57

user3512476
- 1
- 1
1 Answers
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
-
-
oldColor=jButton1.getBackground(); keeps the default color, so you can set it back after your mouse has been released. – Costis Aivalis Apr 08 '14 at 21:00
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