This problem appeared after my last question here. I want to set each button focused and lost focus background to background color which is below main menu (ContentPane which is JPanel), so buttons look like tabs. It couuld be different in different environments, so it is dynamic, so I can't set it manually. Now, If I log ContentPane background it says 238, 238, 238. If I log it inside FocusListener - it also states 238, 238, 238. If I directly set button's background to ContentPane background outside FocusListener - it works, but if I set inside FocusListener - it looks like value is not read and set, but if I set color manually - it works. How this could happen? Setting FocusListener to buttons is the last thing what I do in initialization of main JPanel.
private void setButtonDefaults(JButton but) {//calls once for each menu button to set defaults
but.setBorderPainted(false);
but.setBackground(Color.DARK_GRAY);
but.setForeground(Color.WHITE);
but.setName(but.getText().toLowerCase());
but.setPreferredSize(buttonSize);
but.addActionListener(this);
//add focus listener
but.addFocusListener(new FocusListener() {
@Override
public void focusLost(FocusEvent e) {
Color clr = ContentPane.getBackground();
log(clr + "");//logs that color is 238, 238, 238
JButton button = (JButton) e.getSource();
button.setBackground(clr);//value is not read
//button.setBackground(new Color(238, 238, 238)); //value is read
}
@Override
public void focusGained(FocusEvent e) {
//same as focusLost function
}
});
}
private void enableOnlyOne(JButton but) {
/* calls each time when one of menu buttons are pressed.
All buttons are unpressed and changed colors to black and one
button is set as pressed and changes background color to
ContentPane background color
*/
//disable all
setButtonDisabled(MLibrary);
setButtonDisabled(MScheduler);
setButtonDisabled(MBudget);
setButtonDisabled(MReports);
setButtonDisabled(MManage);
setButtonDisabled(MSettings);
//enable one
but.getModel().setPressed(true);
but.setBackground(ContentPane.getBackground());//value is read perfect
but.setForeground(Color.BLACK);
}
private void setButtonDisabled(JButton but) {
but.getModel().setPressed(false);
but.setBackground(Color.DARK_GRAY);
but.setForeground(Color.WHITE);
}