5

我正在使用这个 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));
        }
    }

我尝试将其重构为以下代码,该代码仅循环通过 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));
        }
    }

任何想法为什么第一个代码块循环并更改所有字体资源,而第二个代码块只循环少数项目?

4

1 回答 1

2

这是一个很好的问题,答案是您使用的方法返回完全不同的对象。

UIManager.getDefaults().keys(); 返回一个枚举。枚举并不担心集合上有重复的对象进行迭代。

UIManager.getDefaults().keySet() 返回一个 Set,因此它不能包含重复的对象。当元素要插入到集合上时,对象的 que equals 方法用于检查对象是否已经在集合上。您正在寻找FontUIResource类型的对象, 并且该对象具有以下实现 os equals 方法:

public boolean equals(Object obj)
    Compares this Font object to the specified Object.
Overrides:
    equals in class Object
Parameters:
    obj - the Object to compare
Returns:
    true if the objects are the same or if the argument is a Font object describing the same font as this object; false otherwise.

因此,在集合上,所有具有描述相同字体的参数的 FontUIResource 类型的键都不会插入到集合中,其中一个键被插入。随后,该集合只有地图上键的一个子集。

有关 java 设置的更多信息:

http://goo.gl/mfUPzp

于 2013-10-19T12:27:20.887 回答