This site requires JavaScript, please enable it in your browser!
Greenfoot back
TheGoldenProof
TheGoldenProof wrote ...

2018/8/11

Drawing many lines between many points

TheGoldenProof TheGoldenProof

2018/8/11

#
public void act() 
    {
        Background b = (Background)getWorld();
        List<Point> points = b.getPoints();
        for (Point p : points) {
            for (Point otherp : points) {
                if (otherp != p) {
                    GreenfootImage lines = new GreenfootImage(1200, 900);
                    lines.setColor(Color.GRAY);
                    lines.drawLine(p.getX(), p.getY(), otherp.getX(), otherp.getY());
                    setImage(lines);
                }
            }
        }
    }
I'm trying to connect some points (locations of the objects in the points list) with all possible lines going between them. For each point I'm trying to draw a line between it and all the other points that aren't it. When I click run, it only draws one line. I only have 5 points so it shouldn't require tons of processing power.
TheGoldenProof TheGoldenProof

2018/8/12

#
OK I fixed it. Changed my code to this (the part that fixed it was taking the GreenfootImage lines = ... and the setBackground(lines) out of the loop):
public class Finder extends Actor
{
    public void act() 
    {
        drawLines();
    }
    public void drawLines() {
        Background b = (Background)getWorld();
        List<Point> points = b.getPoints();
        GreenfootImage lines = new GreenfootImage(1200, 900);
        for (Point p : points) {
            for (Point otherp : points) {
                if (otherp != p) {
                    lines.setColor(Color.GRAY);
                    lines.drawLine(p.getX(), p.getY(), otherp.getX(), otherp.getY());
                }
            }
        }
        getWorld().setBackground(lines);
    }
}
You need to login to post a reply.