Java Swing中的UIManager无法正常工作?/JOptionPane消息背景 [英] UIManager in Java Swing not working consistently? / JOptionPane Message Background
问题描述
我正在尝试在自定义JOptionPane中设置背景颜色,无论如何,我无法获得选项窗格中的消息部分来更改颜色.
I'm trying to set the background color in my custom JOptionPane and no matter what, I cannot get the message part of the option pane to change color.
尝试#1设置窗格的背景和不透明.
Attempt #1 was to set the pane background and opaque.
尝试#2还要遍历窗格的组件,并设置不透明和/或背景属性(如果它们是JPanel或JLabel).
Attempt #2 was to also loop through the pane's components, and set the opaque and/or background attributes if they were JPanel or JLabel.
这不适用于消息部分.据我所知,JPanel甚至不作为组件之一存在.
This did not work for the message part. From what I can see, the JPanel does not even exist as one of the components.
尝试#3是使用UIManager,但这不能始终如一地工作.
Attempt #3 was to use UIManager, however this is not working consistently.
我的意思是,如果您要运行该程序5次,有时背景颜色不会更改,有时会全部更改,有时会其中某些更改.
What I mean is, if you were to run the program 5 times, sometimes no background colors are changed, sometimes they all are changed, and sometimes some of them are changed.
我正在invokeLater线程中运行.
I am running inside an invokeLater thread.
UIManager.put("OptionPane.background",Color.white);
UIManager.put("JOptionPane.background",Color.white);
UIManager.put("Panel.background",Color.white);
UIManager.put("JPanel.background",Color.white);
有什么想法吗?
推荐答案
您可以使用以下解决方法:
You can use following workaround:
JLabel messageLabel = new JLabel("Background is cyan!") {
/**
* {@inheritDoc}
*/
@Override
public void addNotify() {
super.addNotify();
if (getRootPane() != null) {
List<Component> children = findAllChildren(getRootPane());
for (Component comp : children) {
if (!(comp instanceof JButton)) {
comp.setBackground(Color.CYAN);
}
}
}
}
private List<Component> findAllChildren(Component aComp) {
List<Component> result = new ArrayList<Component>();
result.add(aComp);
if (aComp instanceof Container) {
Component[] children = ((Container) aComp).getComponents();
for (Component c : children) {
result.addAll(findAllChildren(c));
}
}
return result;
}
};
JOptionPane.showConfirmDialog(null, messageLabel, "Test title", JOptionPane.YES_NO_CANCEL_OPTION);
这篇关于Java Swing中的UIManager无法正常工作?/JOptionPane消息背景的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!