在JFrame中实现希尔伯特曲线可以通过以下步骤:
以下是一个示例代码:
import javax.swing.JFrame;
import java.awt.Graphics;
import java.awt.Graphics2D;
public class HilbertCurveFrame extends JFrame {
private int level;
public HilbertCurveFrame(int level) {
this.level = level;
setSize(800, 800);
setTitle("Hilbert Curve");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
@Override
public void paint(Graphics g) {
super.paint(g);
Graphics2D g2d = (Graphics2D) g;
drawHilbertCurve(g2d, level, 100, 100, 600, 600, 0);
}
private void drawHilbertCurve(Graphics2D g2d, int level, int x1, int y1, int x2, int y2, int direction) {
if (level == 0) {
g2d.drawLine(x1, y1, x2, y2);
return;
}
int deltaX = (x2 - x1) / 2;
int deltaY = (y2 - y1) / 2;
if (direction == 0) {
drawHilbertCurve(g2d, level - 1, x1, y1, x1 + deltaX, y1 + deltaY, 0);
drawHilbertCurve(g2d, level - 1, x1 + deltaX, y1, x1 + deltaX, y1 + deltaY, 1);
drawHilbertCurve(g2d, level - 1, x1 + deltaX, y1 + deltaY, x1, y1 + deltaY, 0);
drawHilbertCurve(g2d, level - 1, x1, y1 + deltaY, x1, y1, 3);
} else if (direction == 1) {
drawHilbertCurve(g2d, level - 1, x1, y1, x1 + deltaX, y1 + deltaY, 0);
drawHilbertCurve(g2d, level - 1, x1 + deltaX, y1, x1 + deltaX, y1 + deltaY, 1);
drawHilbertCurve(g2d, level - 1, x1 + deltaX, y1 + deltaY, x1, y1 + deltaY, 1);
drawHilbertCurve(g2d, level - 1, x1, y1 + deltaY, x1, y1, 2);
} else if (direction == 2) {
drawHilbertCurve(g2d, level - 1, x1, y1, x1, y1 + deltaY, 3);
drawHilbertCurve(g2d, level - 1, x1, y1 + deltaY, x1 + deltaX, y1 + deltaY, 2);
drawHilbertCurve(g2d, level - 1, x1 + deltaX, y1 + deltaY, x1 + deltaX, y1, 2);
drawHilbertCurve(g2d, level - 1, x1 + deltaX, y1, x1, y1, 1);
} else if (direction == 3) {
drawHilbertCurve(g2d, level - 1, x1, y1, x1, y1 + deltaY, 3);
drawHilbertCurve(g2d, level - 1, x1, y1 + deltaY, x1 + deltaX, y1 + deltaY, 2);
drawHilbertCurve(g2d, level - 1, x1 + deltaX, y1 + deltaY, x1 + deltaX, y1, 0);
drawHilbertCurve(g2d, level - 1, x1 + deltaX, y1, x1, y1, 3);
}
}
public static void main(String[] args) {
HilbertCurveFrame frame = new HilbertCurveFrame(5);
frame.setVisible(true);
}
}
这段代码实现了在JFrame中绘制希尔伯特曲线的功能。你可以根据需要调整窗口大小、阶数和起始点的坐标来观察不同的希尔伯特曲线效果。
领取专属 10元无门槛券
手把手带您无忧上云