背景:
根据文档,方法 SwingUtilities.updateComponentTreeUI()
要求树(什么树?)中的每个组件更新它们自己的UI 属性 调用方法 updateUI()
。
SwingUtilities.updateComponentTreeUI()
强烈建议在我们设置LAF之后调用,调用方法:UIManager.setLookAndFeel(LAFClassName)
,否则LAF 主题无法应用于某些组件,最糟糕的是,某些组件无法重新设计(并且可能会抛出一些异常?)。
我对这类事情新手,并且在发现更具暗示性的SwingUtilities.updateComponentTreeUI()
之后发现了该方法UIManager.setLookAndFeel(LAFClassName)
方法。
在发现 SwingUtilities.updateComponentTreeUI()
之前,我一直遇到一些问题/异常/NullPointerExceptions,事实是我真的不理解它们的原因直到我没有发现 SwingUtilities.updateComponentTreeUI()
方法,这让我明白树中的某些组件无法更新到新的 LAF。
具体/实际问题:
例如,如果我有一个
subJFrame
(动态实例化或由 ActionEvent(点击)触发
mainJFrame
),我在其中设置外观和感觉属性,然后调用 SwingUtilitiesupdateComponentTreeUI()
向其传递对 mainJFrame
的引用:
SwingUtilities.updateComponentTreeUI(mainJFrame)
,
这最后一个是否会更新其所有子组件/subJFrame(从而更新我设置 LAF 的 subJFrame
)?
这不是一个微不足道的问题(同时记住文档所说的内容),因为我在中调用
(这个调用实际上做了什么?),然后我调用 UIManager.setLookAndFeel(LAFClassName)
方法>subJFrameSwingUtilities.updateComponentTreeUI()
方法,向其传递对 mainJFrame
的引用,那么< strong>LAF 主题 将应用于 mainJFrame
的所有子组件?如果某些子组件/subJFrame尚未初始化?
最佳答案
如果您只在创建组件之前设置外观,则永远不需要调用 updateComponentTreeUI
。
如果在创建组件后更改外观,则需要对每个现有组件调用 updateUI()
方法。这就是 updateComponentTreeUI
的辅助功能:它在组件及其包含的所有组件上调用 updateUI()
(以及所有组件) 它们包含的内容;这就是“树”的含义)。
If I have a
subJFrame
where I set the look and feel, and then I callSwingUtilities.updateComponentTreeUI()
passing to it a reference to themainJFrame
: is this going to update all its sub-components/subJFrames (and hence updates the subJFrame where I set the LAF)?
如果 subJFrame
您指的是直接包含在另一个窗口( JInternalFrame
)中的窗口,那么是的。如果您的意思是一个仅从另一个框架打开的框架,但它是一个单独的顶级窗口,那么不会,它不会更新它,因为它不包含在正在更新的组件内。
这是我在更改外观后更新所有顶级窗口的循环:
for (Window w : Window.getWindows()) {
SwingUtilities.updateComponentTreeUI(w);
if (w.isDisplayable() &&
(w instanceof Frame ? !((Frame)w).isResizable() :
w instanceof Dialog ? !((Dialog)w).isResizable() :
true)) w.pack();
}
该循环不会捕获当前未附加到窗口的任何组件。例如,这可以包括 JFileChooser
,如果您在未主动显示这些实例时将它们的实例保留在变量中,在这种情况下,您将需要对它们单独调用 updateComponentTreeUI。
关于java - SwingUtilities.updateComponentTreeUI() 方法是否将当前 L&F 设置为所有 super 组件和子组件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24959878/