Sam Sam - 1 year ago 128
Java Question

How to recursively draw lines in Java?

I have a project i am struggling to get started with, the core of it is around drawing lines recursively perpendicular to one another. I am rather terrible at GUIs for a start. This is what i have so far but i don't know how to implement a recursive method that will draw the lines. This is what i have so far, just simple code to draw a line:

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

public class Test extends JPanel{
private static String n;
private static String r;

public static void main(String[] args){
//n = args[0];
//r = args[1];
//System.out.println("THIS IS MY N: " + n);
//System.out.println("THIS IS MY R: " + r);
JFrame frame = new JFrame();
frame.setSize(400, 400);
frame.add(new Test());

public void paint(Graphics g){
int nn = 10;
for(int i = 0; i < nn; i++){
g.drawLine(400, 200, 50, 250);

So i was thinking along the lines of something like this to do the recursive drawing of the lines:

public static void drawLine(int x1, int y1, int x2, int y2){
if(count == 20){
//Stop or some other condition
g.drawLine(x1, y1, x2, y2);
drawLine(x1+5, y1+5, x2+10, y2+10);

I'm not sure how the paint method actually works into it. I don't think i fully grasp what the paint method is actually doing

Answer Source

The paint() method is the method that is called every time the component is being painted. This will happen initially, when the frame is resized, when the repaint() method is called, etc. In this case you will want to use paintComponent() over paint(). You can save the line as a variable Line2D.Double and use it when you paint.

Example code:

private static Line2D.Double line = new Line2D.Double();
private static int count = 100;

public void paintComponent(Graphics g){
    // use temp line to not effect original line
    Line2D.Double tempLine = line;
    for (int q = 0; q < count; q++){
        g.drawLine((int)tempLine.x1, (int)tempLine.y1, (int)tempLine.x2, (int)tempLine.y2);
        tempLine = new Line2D.Double(tempLine.x1+5, tempLine.y1+5, 
            tempLine.x2+10, tempLine.y2+10);