0
我得到我的代碼運行到目前爲止,除了遞歸部分。我得到一個StackOverflow錯誤,我真的不明白爲什麼,或者如何解決它。當我通過代碼工作時,它似乎在邏輯上很好。遞歸Sierpinsky三角形 - StackOverflow錯誤
public class SierpinskiTriangle {
public static int SIZE = 1000;
JFrame frame;
JPanel panel;
@SuppressWarnings("serial")
public void display() {
frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
panel = new JPanel() {
@Override
public void paint(Graphics g) {
super.paint(g);
paintSierpinskiTriangle(20, 20, 360, (Graphics2D)g);
}
};
panel.addComponentListener(new ComponentAdapter() {
@Override
public void componentResized(ComponentEvent e) {
panel.repaint();
}
});
frame.setLayout(new BorderLayout());
frame.add(panel, BorderLayout.CENTER);
frame.pack();
frame.setSize(SIZE, SIZE);
frame.setVisible(true);
}
public static void main(String[] args) {
SierpinskiTriangle triangle = new SierpinskiTriangle();
triangle.display();
}
public static void paintSierpinskiTriangle(int x, int y, int s, Graphics2D g) {
g.drawLine(x, y, x+s, y);
g.drawLine(x, y, x, y+s);
g.drawLine(x+s, y, x, y+s);
paintSierpinskiTriangle(x, y, s/2, g);
paintSierpinskiTriangle(x+s/2, y, s/2, g);
paintSierpinskiTriangle(x, y+s/2, s/2, g);
}
}
你認爲''paintSierpinkskiTriangle()'每次調用'JPanel'' repaint's時會調用多少次? – CraigR8806
對不起,我不明白。 –
我認爲你在'paintSierpinskiTriangle'中缺少一些檢查,你將不會**停止遞歸。 – luk2302