Java: 用drawLine画一个矩形螺旋

Java: draw a rectangular spiral with drawLine

我正在做一个 Java 编程练习,我应该用 drawLine 方法绘制一个矩形螺旋。到目前为止,这是我所拥有的,但螺旋上升看起来不完整。

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);     
    }
}

这是输出:

我尝试用 for 循环添加第五行,但结果仍然不完整。 感谢任何帮助,谢谢!

在您的第一个 g.drawLine 中,您需要从 y 的中心减去 (20 * i),才能不开始

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

但在这里:

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

所以使用

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

试试这个解决方案:

package mainpack;

import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.RenderingHints;

import javax.swing.JPanel;

public class SpiralQuadPanel extends JPanel {

    private static final long serialVersionUID = 1L;

    @Override
    public void paintComponent(Graphics g) {
        super.paintComponent(g);

        Graphics2D g2d = (Graphics2D)g;

        g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
                RenderingHints.VALUE_ANTIALIAS_ON);

        g2d.setRenderingHint(RenderingHints.KEY_RENDERING,
                RenderingHints.VALUE_RENDER_QUALITY);

        int x = getWidth() / 2;
        int y = getHeight() / 2;

        for (int i = 0; i < 8; i++) {

            int t = i * 20;

            g2d.drawLine(x + t, y + t, x + t, y + 20 + t);
            g2d.drawLine(x + t, y + 20 + t, x - 20 - t , y + 20 + t);
            g2d.drawLine(x - 20 - t, y + 20 + t, x - 20 - t, y - 20 - t);
            g2d.drawLine(x - 20 - t, y - 20 - t, x + 20 + t, y - 20 - t);
            g2d.drawLine(x  + 20 + t, y - 20 - t, x + 20 + t, y + 20 + t);
        }
    }
}