我有這段代碼,橢圓形狀應該在實現可運行類時自動移動到右側。但它似乎並沒有移動。任何幫助深表感謝。提前致謝。當在java中使用線程實現可運行時,形狀不會移動
package movingball;
import java.awt.Color;
import java.awt.Graphics;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class MovingBall extends JPanel{
private static final int x = 30;
private static final int y = 30;
public MovingBall(){
setBackground(Color.BLACK);
}
public MovingBall(int x, int y){
x = this.x;
y = this.y;
repaint();
}
public static void main(String[] args) {
JFrame frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(500,700);
MovingBall movingBall = new MovingBall();
frame.add(movingBall);
frame.setVisible(true);
調用線程分配球對象
BallUsingThread ball = new BallUsingThread(x, y);
Thread first = new Thread(ball);
first.start();
}
@Override
public void paintComponent(Graphics canvas){
super.paintComponent(canvas);
canvas.setColor(Color.BLUE);
canvas.fillOval(x, y, 100, 100);
}
}
/*Here is the second class. Where the oval shape should be moving. Any `suggestions here? Also just let me know if there are some codes need to be adjusted.*/
class BallUsingThread implements Runnable{
int x = 30;
int y = 30;
public BallUsingThread(int x, int y){
this.x = x;
this.y = y;
}
@Override
public void run() {
for(;;){
x++;
try {
Thread.sleep(2000);
} catch (InterruptedException ex) {
System.out.printf("Error",ex);
}
}
}
}
明白了你的觀點。謝謝。 –