【发布时间】:2012-02-06 00:05:57
【问题描述】:
这个问题出现在my last question here之后。我想将每个按钮的焦点和失去焦点的背景设置为主菜单下方的背景颜色(ContentPane 是 JPanel),所以按钮看起来像标签。在不同的环境中可能会有所不同,所以它是动态的,所以我不能手动设置它。现在,如果我记录 ContentPane 背景,它会显示 238、238、238。如果我在 FocusListener 中记录它 - 它还会显示 238、238、238。如果我直接将按钮的背景设置为 FocusListener 外部的 ContentPane 背景 - 它可以工作,但如果我设置在 FocusListener 内部 - 看起来没有读取和设置值,但如果我手动设置颜色 - 它可以工作。这怎么可能发生?将 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(请查看链接),我将能够更好地理解这一点。祝你好运!
-
请问是否多次调用了focusLost?
-
我查过了。每次单击其中一个按钮时都会调用它,但
ContentPane.getBackground()每次都记录相同的值:javax.swing.plaf.ColorUIResource[r=238,g=238,b=238] -
“所以按钮看起来像标签。” 我在您之前的问题的屏幕截图中看不到任何使用
JTabbedPane和自定义 PLAF 无法实现的内容.但是,您似乎并没有听取所提供的好建议(至少,不是在 cmets 中)。 -
@Andrew Thompson 请...,我看不到有什么可以听的,但可能让我瘫痪了 *** 我持续失眠超过 2 天
标签: java swing focus background-color jbutton