刚写了一个显示动态动画的程序。顺便说一句,它运行但问题是背景继续以快速的速度闪烁黑白。我用Google搜索了它,但没有得到合适的答案。这是代码: 对于主要方法 -
import java.awt.*;
import javax.swing.*;
import javax.swing.ImageIcon;
import javax.swing.JFrame;
public class nam2 {
public static void main(String[] args){
nam2 b= new nam2();
b.run();
}
private Sprite sprite; //class to control characteristics of image
private Animation a; //class to control animation
private ScreenManager s; //class to control monitor screen
private Image bg; //an image
private static final DisplayMode modes1[] = { // List of desired DisplayModes
new DisplayMode(800,600,32,0),
new DisplayMode(800,600,25,0),
new DisplayMode(800,600,16,0),
new DisplayMode(640,480,32,0),
new DisplayMode(640,480,24,0),
new DisplayMode(1920,1080,16,0),
};
//load images and add scenes
public void loadImages(){
bg = new ImageIcon("G:\\bg2.jpg").getImage();
Image face1 = new ImageIcon("G:\\naman1.jpg").getImage();
Image face2 = new ImageIcon("G:\\3.jpg").getImage();
a = new Animation();
a.addScene(face1,500);
a.addScene(face2,500);
sprite = new Sprite(a);
sprite.setVelocityX(0.3f);
sprite.setVelocityY(0.3f);
}
//run method call from main method
public void run(){
s = new ScreenManager();
try{
DisplayMode dm = s.findFirstCompDisplayMode(modes1);
s.setFullScreen(dm);
loadImages();
movieLoop();
}finally{s.restoreScren();}
}
public void movieLoop(){
long startingTime = System.currentTimeMillis();
long cumTime = startingTime;
while(cumTime - startingTime <10000){
long timePassed = System.currentTimeMillis() - cumTime ;
cumTime += timePassed;
update(timePassed);
//draw and update screen
Graphics2D g = s.getGraphics();
draw(g);
g.dispose();
s.update();
try{
Thread.sleep(20);
}catch(Exception e){}
}
}
//draw method
public void draw(Graphics g){
g.drawImage(bg, 0, 0, null);
g.drawImage(sprite.getImage(), Math.round(sprite.getX()),Math.round(sprite.getY()),null);
}
//update method
private void update(long timePassed) {
if(sprite.getX() < 0 ){
sprite.setVelocityX(Math.abs(sprite.getVelocityX()));
}else if(sprite.getX() + sprite.getWidth() >= s.getWidth()){
sprite.setVelocityX(-Math.abs(sprite.getVelocityX()));
}
if(sprite.getY() < 0 ){
sprite.setVelocityY(Math.abs(sprite.getVelocityY()));
}else if(sprite.getY() + sprite.getHeight() >= s.getHeight()){
sprite.setVelocityY(-Math.abs(sprite.getVelocityY()));
}
sprite.update(timePassed);
}
}
我上传了只有主要类的代码。如果需要其他课程代码,请告诉我。当我改变线程的休眠时间时,它不是与线程相关的东西,闪烁的速度会发生变化。所以我写这个问题的主要问题是: 为什么屏幕会闪烁黑到白,再次连续变黑。