I am having problem with drawing multiple lines during repaint. The code is as follows:
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);
}
}
}
it draws line only for the last pair in the HashMap and the test line that i added.
Thanks in advance for help.
Don’t remove the pair from the iterator.
This is an un-neccesary step if it’s a temporary hashmap, and it’s a critical problem if it’s a reused hashmap. This removes the item from the underlying hashmap. So if
matchEncDec()is returning a hashmap that is being reused, you will only paint each line once because the pair will be removed from the hashmap once it gets painted.It would be helpful to see the
matchEncDec()method, but I would just be checking to see if you are returning a reference to the same hashmap with each call. If that’s the case, then this is definitely the problem.