此問題出現在my last question here之後。我想將每個按鈕設置爲焦點並將焦點背景設置爲主菜單(ContentPane是JPanel)下面的背景顏色,因此按鈕看起來像標籤。它在不同的環境中有所不同,所以它是動態的,所以我不能手動設置它。現在,如果我記錄ContentPane背景,它說238,238,238。如果我將它記錄在FocusListener中 - 它也表示238,238,238。如果我直接將按鈕的背景設置爲FocusListener外部的ContentPane背景 - 它可以工作,但如果我設置了在FocusListener裏面 - 它看起來像沒有讀取和設置值,但如果我手動設置顏色 - 它的作品。這可能如何發生?將FocusListener設置爲按鈕是我在主JPanel初始化時所做的最後一件事。似乎沒有在FocusListener中讀取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);
}
對於我來說,我希望能多更好地理解這個如果您可以創建併發布[sscce](http://sscce.org)(請檢查鏈接)。祝你好運! – 2012-01-09 12:58:36
CAn請檢查focusLost是否被多次調用? – 2012-01-09 13:02:22
我檢查了它。每次點擊一個按鈕時調用它,但每次使用'ContentPane.getBackground()'記錄相同的值:'javax.swing.plaf.ColorUIResource [r = 238,g = 238,b = 238]' – 2012-01-09 13:31:41