为什么重画只绘制一条线?

时间:2012-06-21 11:54:58

标签: java swing

我在重绘期间绘制多条线时遇到问题。代码如下:

public void paintComponent(Graphics g){
    Graphics2D g2d = (Graphics2D) g;

    Map<Device, Device> devMap = matchEncDec();
    if(devMap != null){
        Iterator<?> it = devMap.entrySet().iterator();
        while(it.hasNext()){
            Map.Entry<Device, Device> pair =  (Entry<Device, Device>) it.next();
            it.remove();

            g2d.setColor(Color.BLUE);
            g2d.drawLine(pair.getKey().getLocationOnScreen().x + 150, pair.getKey().getLocationOnScreen().y, 
                    pair.getValue().getLocationOnScreen().x + 150, pair.getValue().getLocationOnScreen().y);

            g2d.drawLine(50, 50, 500, 550);
        }
    }
}

它仅为HashMap中的最后一对和我添加的测试行绘制线条。 在此先感谢您的帮助。

1 个答案:

答案 0 :(得分:2)

请勿从迭代器中删除该对。

it.remove();

如果它是一个临时的hashmap,这是一个不必要的步骤,如果它是一个重用的hashmap,这是一个关键问题。这将从基础hashmap中删除该项。因此,如果matchEncDec()返回正在重用的散列映射,则只会绘制每一行一次,因为该对将在绘制后从散列映射中删除。

查看matchEncDec()方法会很有帮助,但我只是检查你是否在每次调用时都返回对同一个hashmap的引用。如果是这样的话,那肯定是问题。

相关问题