Java 2D-Graphics:Animate Fractal树

时间:2014-03-31 08:16:08

标签: java swing animation tree thread-sleep

我正在尝试画一棵分形树。

它将绘制树,但我想制作一个动画,以便树可以从它的“树干”生长?还可以使动画流畅吗?

如果我使用Thread.sleep方法,它会使树非常奇怪。

有人可以帮助我吗?非常感谢

这是我的代码:

import java.awt.BasicStroke;
import java.awt.Canvas;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.RenderingHints;

import javax.swing.JFrame;

public class FractalTree extends Canvas {

      private JFrame frame;

      //Breedte en hoogte voor GUI
      private final int WINDOW_WIDTH = 1280;
      private final int WINDOW_HEIGHT = 720;

      public FractalTree() {
        frame = new JFrame("Fractal Tree");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setSize(WINDOW_WIDTH, WINDOW_HEIGHT);
        frame.setLocationRelativeTo(null);
        frame.setResizable(false);
        frame.add(this);
        frame.setVisible(true);
      }

      public static void main(String[] args) {
        FractalTree ft = new FractalTree();
        ft.setVisible(true);
        ft.setBackground(Color.black);
      }


class FractalPanel extends JPanel implements ActionListener {

private int x;
private int y;
private int xNew;
private int yNew;
private double angle;
private int depth;

public FractalPanel() {
    setBackground(Color.black);
    Timer timer = new Timer(200, this);
}

public void paintComponent(Graphics g) {
    g.setColor(Color.cyan);
    drawFractalTree(g, WINDOW_WIDTH / 2, WINDOW_HEIGHT - 75, -90, 11);
  }

  public void drawFractalTree(Graphics g, int x, int y, double angle, int depth) {

    if (depth == 0) {
    } else {

      int xNew = x + (int) (Math.cos(Math.toRadians(angle)) * depth * 10.0);
      int yNew = y + (int) (Math.sin(Math.toRadians(angle)) * depth * 10.0);

      Graphics2D g2d = (Graphics2D) g;
      g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);

      g2d.setStroke(new BasicStroke(0.5f * depth));
      g2d.drawLine(x, y, xNew, yNew);

      drawFractalTree(g, xNew, yNew, angle + 30, depth - 1);
      drawFractalTree(g, xNew, yNew, angle - 30, depth - 1);
    }
  }


public void actionPerformed(ActionEvent e) {
    if (depth == 0) {
    } else {

      int xNew = x + (int) (Math.cos(Math.toRadians(angle)) * depth * 10.0);
      int yNew = y + (int) (Math.sin(Math.toRadians(angle)) * depth * 10.0);
      repaint();
    }

}

} }

PS:对不起我的英文

1 个答案:

答案 0 :(得分:4)

不要混合swing和awt(CanvasJFrame)。您可以扩展JPanel并覆盖paintComponent(Grahics g)方法,而不是使用画布,您可以在其中执行所有绘图。

不要在油漆区打电话给Thread.sleep(10);。它只是阻止事件调度程序线程并阻止绘制。

而是创建一个Timer来调用每个所需的时间间隔。在Timer的操作中,更改模型(x,y等)并调用repaint()以反映更改。