我想让画面在画布上移动 .
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);
}
}
然后控制台返回
GraphicsProgram.java:43:错误:未报告的异常InterruptedException;必须被捕获或声明被抛出Thread.sleep(2000); ^ 1错误
我真的不明白为什么我的 Thread.sleep()
没有工作,因为我已经搜索过了,这正是他们所说的 .
2 回答
通常,在
Move
方法中使用Thread.sleep()
是不好的做法 . 但是,如果这是你打算做的:这是一个编译错误,抱怨可能没有被捕获的异常,请尝试使用try-catch语句包围
Thread.sleep(2000)
,例如:InterruptedException
是一个已检查的异常,您必须catch
,如下所示:但是,正如@Hovercraft强调的那样,在绘画方法中调用睡眠不是一个好习惯 .