我正在尝试创建一个简单的 Java 小程序,它应该在 Java 中显示生成的希尔伯特曲线。我把我的代码和书中的一些代码混在一起了,现在我卡住了。我没有得到我想要的显示。
这是整个代码:
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
//Defining classes
public class HilbertCurves extends JApplet {
//Declare data fields
private JTextField OrderTextfield = new JTextField("0",5);
private HilbertCurve hilbertCurvePanel = new HilbertCurve();
//Constructors
public HilbertCurves() {
//Creating a panel object
JPanel panel = new JPanel();
panel.add(new JLabel("Enter the order : "));
panel.add(OrderTextfield);
OrderTextfield.setHorizontalAlignment(SwingConstants.RIGHT);
//Adding panel to the app
add(hilbertCurvePanel);
add(panel, BorderLayout.SOUTH);
OrderTextfield.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
hilbertCurvePanel.setOrder(Integer.parseInt(OrderTextfield.getText()));
}
});
}
private static class HilbertCurve extends JPanel {
//Declare variables
private int length;
private int order=1;
private int a,b;
//For order
public void setOrder(int order){
this.order=order;
repaint();
}
public void paintComponent(Graphics g){
super.paintComponent(g);
//Find the length
length = Math.min(getWidth(),getHeight());
for (int i = 0; i < order; i++)
length/=2;
//Reset
a = length/2; b=length/2;
Upper(g,order);
}
//Display upper
private void Upper(Graphics g, int order){
if (order >0){
Left(g, order-1);
lineNewPosition(g,0,length);
Upper(g,order-1);
lineNewPosition(g,0,-length);
right(g, order-1);
}
}
//Display left
private void Left(Graphics g, int order){
if (order>0){
Upper(g,order-1);
lineNewPosition(g,length,0);
Left(g,order-1);
lineNewPosition(g,0,length);
Left(g,order-1);
lineNewPosition(g,-length,0);
Down(g,order-1);
}
}
//Display right
private void right(Graphics g, int order){
if (order>0){
Down(g,order-1);
lineNewPosition(g,-length,0);
right(g,order-1);
lineNewPosition(g,0,-length);
right(g,order-1);
lineNewPosition(g,length,0);
Upper(g,order-1);
}
}
//Display down
private void Down(Graphics g, int order){
if (order>0){
right(g,order-1);
lineNewPosition(g,0,-length);
Down(g,order-1);
lineNewPosition(g,-length,0);
Down(g,order-1);
lineNewPosition(g,0,length);
Left(g,order-1);
}
}
//Draw a line
public void lineNewPosition(Graphics g, int deltaX, int deltaY){
g.drawLine(a, b, a + deltaX, b + deltaY);
a+=deltaX;
b+=deltaY;
}
}
public static void main(String[] args) {
JApplet applet = new HilbertCurves();
applet.init();
applet.start();
JFrame frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setTitle("Visualising Hilbert Curves");
frame.getContentPane().add(applet,BorderLayout.CENTER);
frame.setSize(512,512);
frame.setVisible(true);
}
}
在我看来,定义绘图函数时有问题,但此时我似乎无法找出解决方案。这是我得到的输出(与我的目标不同):