如何解决我正在尝试使用Runnable和.sleep使我的JFrame绘图具有动画效果,无法正常工作
我递归地绘制了FernFractal,我想使蕨类在代码运行时看起来像是在动画。
public void run() {
try {
while(true) {
componentsDrawn = 0;
componentsToDraw++;
this.repaint();
for (int i = 0; i < FractalTester.speed; i++) {
Thread.sleep(100);
}
}
}
catch (InterruptedException e) {}
}
^上面是我当前的代码,该代码使用repaint和sleep()使其看起来像是分形动画,但是当我运行代码时,它只是打印出分形,并且没有任何动画。
import java.awt.Graphics;
import java.util.Scanner;
import java.util.regex.Matcher;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.WindowConstants;
public class FernFractal {
public static int MAXDIM = 600;
public static int speed = 1;
public static int type = 1;
public static void main(String[] args) {
// TODO Auto-generated method stub
JFrame frame = new JFrame("FernBoi");
frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
frame.setSize(MAXDIM,MAXDIM);
Fern f = new Fern();
frame.add(f);
frame.setVisible(true);
new Thread(f).start();
}
}
class Fern extends JPanel implements Runnable{
private static final long serialVersionUID = 1L;
private static int componentsDrawn = 0;
private static int componentsToDraw = 0;
@Override
public void paintComponent(Graphics g) {
// TODO Auto-generated method stub
super.paintComponent(g);
int startX = (int) (FernFractal.MAXDIM * 0.3);
int startY = (int) (FernFractal.MAXDIM * 0.6);
int startLen = (int) (FernFractal.MAXDIM * 0.1);
drawFractal1(g,startX,startY,startLen,(Math.PI/3));
}
private void drawFractal1(Graphics g,int x1,int y1,int segmentLength,double angle) {
int currX = x1;
int currY = y1;
int nextX = currX + (int) (segmentLength * Math.cos(angle));
int nextY = currY - (int) (segmentLength * Math.sin(angle));
// Note that whenever you draw a line,it should be in an if statement
// like the one below,so that you can progressively render the fractal
if(segmentLength <= 1) return;
if (componentsDrawn < componentsToDraw) {
componentsDrawn++;
g.drawLine(currX,currY,nextX,nextY);
//left
drawFractal1(g,nextY,(int)(segmentLength*0.6),(angle + ((Math.PI) / 2)) );
//right
drawFractal1(g,(angle - ((Math.PI) / 2)) );
//center
drawFractal1(g,(int)(segmentLength*0.9),(angle - ((Math.PI) / 36)) );
}
}
public void run() {
try {
while(true) {
componentsDrawn = 0;
componentsToDraw++;
this.repaint();
for (int i = 0; i < FractalTester.speed; i++) {
Thread.sleep(100);
}
}
}
catch (InterruptedException e) {}
}
}
^上面是我在FernFractal类中的全部代码。我是在某个地方放错了方法还是在某处我的计算不正确?有人可以帮我弄清楚为什么动画不起作用吗?非常感谢。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。