Java: draw a rectangular spiral with drawLine

user3266259 picture user3266259 · Apr 14, 2015 · Viewed 7k times · Source

I'm working on a Java programming exercise where I'm supposed to draw a rectangular spiral with the drawLine method. Here's what I have so far, but the spiral comes up looking incomplete.

import java.awt.Graphics; 
import javax.swing.JPanel;
import javax.swing.JFrame;

public class RectSpiral extends JPanel
{
    public void paintComponent(Graphics g)
    {
        int width = getSize().width;
        int height = getSize().height;

        int widthCenter = width / 2;
        int heightCenter = height / 2;

        for (int i = 0; i < 4 ; i++)
        {
            g.drawLine(widthCenter + (20 * i), heightCenter + (20 * i), widthCenter + (20 * i), heightCenter + 20 + (20 * i));
            g.drawLine(widthCenter + (20 * i), heightCenter + 20 + (20 * i), widthCenter - 20 - (20 * i), heightCenter + 20 + (20 * i));
            g.drawLine(widthCenter - 20 - (20 * i), heightCenter + 20 + (20 * i), widthCenter - 20 - (20 * i), heightCenter - 20 - (20 * i));
            g.drawLine(widthCenter - 20 - (20 * i), heightCenter - 20 - (20 * i), widthCenter + 20 + (20 * i), heightCenter - 20 - (20 * i));
        }
    }

    public static void main(String[] args)
    {
        RectSpiral panel = new RectSpiral();

        JFrame application = new JFrame();

        application.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        application.add(panel);      
        application.setSize(300, 300); 
        application.setVisible(true);     
    }
}

This is the output:

enter image description here

I've tried adding a fifth line withing the for loop, but the result still comes up incomplete. Any help is appreciated, thank you!

Answer

Pshemo picture Pshemo · Apr 14, 2015

In your first g.drawLine you need to subtract (20 * i) from center of y, to not start

|
|
|
center
|
|<-center + (20 * i)
|

but here:

|
|<-center - (20 * i)
|
center
|
|
|

so use

g.drawLine(widthCenter + (20 * i), heightCenter - (20 * i),
//                                              ^---------------change
           widthCenter + (20 * i), heightCenter + 20 + (20 * i));