Ale*_*ard 5 java swing key uimanager
我正在使用此stackOverflow帖子中的代码,它完成了我的期望:
Enumeration<Object> keys = UIManager.getDefaults().keys();
while (keys.hasMoreElements()) {
Object key = keys.nextElement();
Object value = UIManager.get(key);
if (value instanceof FontUIResource) {
FontUIResource orig = (FontUIResource) value;
Font font = new Font(orig.getFontName(), orig.getStyle(), orig.getSize());
UIManager.put(key, new FontUIResource(font));
}
}
Run Code Online (Sandbox Code Playgroud)
我试图将它重构为以下代码,它只循环遍历javax.swing.plaf中的几个类而不是完整的组件集.我试过挖掘swing API和HashTable API,但我觉得我仍然缺少一些明显的东西.
for(Object key : UIManager.getDefaults().keySet()){
Object value = UIManager.get(key);
if(value instanceof FontUIResource){
FontUIResource orig = (FontUIResource) value;
Font font = new Font(orig.getFontName(), orig.getStyle(), orig.getSize());
UIManager.put(key, new FontUIResource(font));
}
}
Run Code Online (Sandbox Code Playgroud)
任何想法为什么第一个代码块循环并更改所有字体资源,而第二个代码只循环几个项目?
小智 2
这是一个很好的问题,答案是您使用的方法返回完全不同的对象。
\n\nUIManager.getDefaults().keys(); 返回一个枚举。枚举并不担心集合上有重复的对象进行迭代。
\n\nUIManager.getDefaults().keySet() 返回一个 Set,因此它不能包含重复的对象。当要在集合上插入元素时,对象的 que equals 方法用于检查对象是否已在集合上准备好。您正在寻找FontUIResource类型的对象 ,该对象具有以下实现 os equals 方法:
\n\n\n\n\nRun Code Online (Sandbox Code Playgroud)\npublic boolean equals(Object obj)\n Compares this Font object to the specified Object.\nOverrides:\n equals in class Object\nParameters:\n obj - the Object to compare\nReturns:\n true if the objects are the same or if the argument is a Font object describing the same font as this object; false otherwise.\n
因此,在集合上,具有描述相同字体的参数的 FontUIResource 类型的所有键都不会插入到插入的集合中。因此,该集合仅具有映射上的键的子集。
\n\n有关 java 设置的更多信息:
\n\n\n