gpt4 book ai didi

java - Java Swing 中的 UIManager 无法一致工作?/JOptionPane 消息背景

转载 作者:行者123 更新时间:2023-12-02 04:39:47 25 4
gpt4 key购买 nike

我正在尝试在自定义 JOptionPane 中设置背景颜色,但无论如何,我都无法让选项 Pane 的消息部分更改颜色。

尝试#1 是将 Pane 背景设置为不透明。

尝试 #2 还循环遍历 Pane 的组件,并设置不透明和/或背景属性(如果它们是 JPanel 或 JLabel)。

这对于消息部分不起作用。据我所知,JPanel 甚至不作为组件之一存在。

尝试 #3 是使用 UIManager,但这并不能始终如一地工作。

我的意思是,如果你运行程序5次,有时背景颜色没有改变,有时背景颜色全部改变,有时其中一些改变。

我正在 invokeLater 线程内运行。

UIManager.put("OptionPane.background",Color.white);
UIManager.put("JOptionPane.background",Color.white);
UIManager.put("Panel.background",Color.white);
UIManager.put("JPanel.background",Color.white);

有什么想法吗?

最佳答案

您可以使用以下解决方法:

    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 - Java Swing 中的 UIManager 无法一致工作?/JOptionPane 消息背景,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30298489/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com