我試圖讓畫面在畫布上移動。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);
}
}
控制檯然後返回
GraphicsProgram.java:43: error: unreported exception InterruptedException; must be caught or declared to be thrown Thread.sleep(2000); ^1 error
我真的不明白爲什麼,因爲我已搜查了起來,這是他們把什麼我Thread.sleep()
是行不通的。
' 「我真的不明白爲什麼我的Thread.sleep()不工作,因爲我已經搜索了它,這正是他們所做的。」 - 請在這裏顯示一個鏈接到一個高度投票的答案,這將把一個線程在繪畫方法中間休息。你需要的解決方案是一個Swing Timer,而不是'Thread.sleep'。 –
https://docs.oracle.com/javase/tutorial/essential/exceptions/catchOrDeclare.html – shmosel