I want to have custom colors according to the mouse events (mouse enter, exit, pressed, etc). So to accomplish this, I wrote the code below. It is fine for everything, except in the case of the mouse pressed event, which does nothing.
It only works if I override the color in the UIManager
like this UIManager.put("Button.select", Color.red);
. The problem with the UIManager
is that it will change for all my buttons.
Can anyone tell me what I might be doing wrong or what is the best approach to accomplish what I'm trying to do?
My Code:
final JButton btnSave = new JButton("Save");
btnSave.setForeground(new Color(0, 135, 200).brighter());
btnSave.setHorizontalTextPosition(SwingConstants.CENTER);
btnSave.setBorder(null);
btnSave.setBackground(new Color(3, 59, 90));
btnSave.addMouseListener(new MouseListener() {
@Override
public void mouseReleased(MouseEvent e) {
btnSave.setBackground(new Color(3, 59, 90));
}
@Override
public void mousePressed(MouseEvent e) {
// Not working :(
btnSave.setBackground(Color.pink);
}
@Override
public void mouseExited(MouseEvent e) {
btnSave.setBackground(new Color(3, 59, 90));
}
@Override
public void mouseEntered(MouseEvent e) {
btnSave.setBackground(new Color(3, 59, 90).brighter());
}
@Override
public void mouseClicked(MouseEvent e) {
btnSave.setBackground(new Color(3, 59, 90).brighter());
}
});
Edit1:
So, instead of MouseListener
, I'm using ChangeListener
and ButtonModel
as suggested by mKorbel. With this code I'm still not observing any changes on mouse pressed in the button except when I press and drag outside the button. Any thoughts?
btnSave.getModel().addChangeListener(new ChangeListener() {
@Override
public void stateChanged(ChangeEvent e) {
ButtonModel model = (ButtonModel) e.getSource();
if (model.isRollover()) {
btnSave.setBackground(new Color(3, 59, 90).brighter());
} else if (model.isPressed()) {
btnSave.setBackground(Color.BLACK);
} else {
btnSave.setBackground(new Color(3, 59, 90));
}
}
});
JButton
? – Absa