我正在进行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循环添加第五行,但结果仍然不完整。 感谢任何帮助,谢谢!
答案 0 :(得分:2)
在您的第一个g.drawLine
中,您需要从(20 * i)
的中心减去y
,以便不启动
|
|
|
center
|
|<-center + (20 * i)
|
但是在这里:
|
|<-center - (20 * i)
|
center
|
|
|
所以使用
g.drawLine(widthCenter + (20 * i), heightCenter - (20 * i),
// ^---------------change
widthCenter + (20 * i), heightCenter + 20 + (20 * i));
答案 1 :(得分:0)
试试这个解决方案:
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);
}
}
}