graphics - Java: draw a rectangular spiral with drawLine -
i'm working on java programming exercise i'm supposed draw rectangular spiral drawline method. here's have far, spiral comes 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; (int = 0; < 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 output:
i've tried adding fifth line withing loop, result still comes incomplete. appreciated, thank you!
in first g.drawline
need subtract (20 * i)
center of y
, 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));
Comments
Post a Comment