如何在Java中递归画线?

How to recursively draw lines in Java?

我有一个项目我正在努力开始,它的核心是围绕递归地相互垂直地绘制线。一开始,我在 GUI 方面相当糟糕。这是我到目前为止所拥有的,但我不知道如何实现一个递归方法来画线。这是我到目前为止所拥有的,只是简单的代码来画一条线:

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());
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setVisible(true);
    }

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

所以我想按照这样的思路来递归绘制线条:

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

我不确定 paint 方法实际上是如何工作的。我不认为我完全理解 paint 方法实际上在做什么

paint()方法是每次绘制组件时调用的方法。这将在最初、调整框架大小时、调用 repaint() 方法等时发生。在这种情况下,您将需要使用 paintComponent() over paint()。可以将线条保存为变量Line2D.Double,画画时使用。

示例代码:

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

@Override
public void paintComponent(Graphics g){
    super.paintComponent(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);
    }
}