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();
}
}