Java program to generate square spiral.

Note that spiral size should be uneven number in order to generate it properly.
Main.java
import javax.imageio.ImageIO; import java.io.File; // 2018 TheFlyingKeyboard and released under MIT License // theflyingkeyboard.net public class Main { public static void main(String[] args) { SquareSpiral sierpinskiTriangle = new SquareSpiral(); try { ImageIO.write(sierpinskiTriangle.generate(15), "png", new File("SquareSpiral.png")); } catch (Exception e) { e.printStackTrace(); } } }
SquareSpiral.java
import java.awt.*; import java.awt.image.BufferedImage; // 2018 TheFlyingKeyboard and released under MIT License // theflyingkeyboard.net public class SquareSpiral { private final Color foregroundColor; private final Color backgroundColor; public SquareSpiral() { this.foregroundColor = Color.BLACK; this.backgroundColor = Color.WHITE; } public SquareSpiral(final Color foregroundColor, final Color backgroundColor) { this.foregroundColor = foregroundColor; this.backgroundColor = backgroundColor; } public BufferedImage generate(final int spiralSize){ BufferedImage bufferedImage = new BufferedImage(spiralSize, spiralSize, BufferedImage.TYPE_INT_RGB); Graphics2D graphics2D = bufferedImage.createGraphics(); graphics2D.setColor(backgroundColor); graphics2D.fillRect(0 ,0, spiralSize, spiralSize); graphics2D.setColor(foregroundColor); int x = spiralSize / 2; int y = spiralSize / 2; int length = 1; int counter = 0; while(x >= 0 && y >= 0 && x < spiralSize && y < spiralSize){ switch (counter) { case 0: graphics2D.drawLine(x, y, x + length, y); x += length; break; case 1: graphics2D.drawLine(x, y, x, y + length); y += length; break; case 2: graphics2D.drawLine(x, y, x - length, y); x -= length; break; case 3: graphics2D.drawLine(x, y, x, y - length); y -= length; counter = -1; break; } ++counter; ++length; } return bufferedImage; } }
Java Square Spiral
Hello,
Im very new to java, beginner 😉
I use a mac.
Which program do I use to create and run this spiral?
I want to play around with the shapes and sizes and learn about java.
Thanks for your help,
Cake