1. java繪圖
要移動就要Thread
你要實現一個移動的話就要用到線程,移動實際上就是每隔一段時間改變一個圖形在畫板上開始的坐標,然後再重畫畫板,用一個線程可以使用繼承Thread 或者實現Runnable介面
例如下面這個是個移動的月亮
import java.awt.*;
import javax.swing.*;
public class Test extends JFrame implements Runnable {
static int i = 10;
static int j = 440;
public Test() {
this.setSize(500, 500);
this.setVisible(true);
this.setResizable(false);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
public void paint(Graphics g) {
super.paint(g);
g.setColor(Color.BLACK);
g.fillRect(0, 0, 500, 500);
g.setColor(Color.white);
g.fillOval(i, j, 60, 60);
g.setColor(Color.gray);
g.setColor(Color.BLACK);
g.fillOval(i - 20, j - 20, 60, 60);
}
public void run() {
while (true) {
try {
Thread.sleep(500);
} catch (InterruptedException e) {
e.printStackTrace();
}
if (i >= 155) {
i += 5;
j += 15;
}
if (i < 155) {
i += 5;
j -= 15;
}
if (i >= 305) {
i = 10;
j = 440;
}
System.out.println(i + " " + j);
this.repaint();
}
}
public static void main(String args[]) {
new Thread(new Test()).start();
}
}