wait() 和 Thread.sleep() 不起作用



我试图让图片在画布上移动。

import java.awt.*; class GraphicsProgram extends Canvas{
static int up = 0;

public GraphicsProgram(){
setSize(700, 700);
setBackground(Color.white);
}
public static void main(String[] argS){
//GraphicsProgram class is now a type of canvas
//since it extends the Canvas class
//lets instantiate it
GraphicsProgram GP = new GraphicsProgram();   
//create a new frame to which we will add a canvas
Frame aFrame = new Frame();
aFrame.setSize(700, 700);
//add the canvas
aFrame.add(GP);
aFrame.setVisible(true);
}
public void paint(Graphics g){

Image img1 = Toolkit.getDefaultToolkit().getImage("Code.jpg"); 
g.drawImage(img1, up, up, this);         }
public void  Move() {   up = up + 1;    Move();

Thread.sleep(2000);
}

}

然后控制台返回

图形程序.java:43:错误:未报告的异常 中断异常;必须被抓住或宣布被扔掉 线程睡眠(2000); ^ 1 错误

我真的不明白为什么我的Thread.sleep()不起作用,因为我已经搜索了它,这正是他们所说的。

通常,在Move方法中使用Thread.sleep()是一种不好的做法。 但是,如果这是您打算做的:

这是一个编译错误,抱怨有一个可能无法捕获的异常,请尝试用 try-catch 语句包围您的Thread.sleep(2000),例如:

try {
Thread.sleep(2000);
} catch (InterruptedException e) {
e.printStackTrace();
}
InterruptedException

是一个选中的异常,你必须catch它,如下所示:

try {
Thread.sleep(2000);
} catch (InterruptedException e) {
e.printStackTrace();
}

但是,正如@Hovercraft所强调的,在绘画方法中称睡眠不是一种好的做法。

最新更新