编写JAVA线程两个正方形分别从左上角移动 80
展开全部
lz 你好
我做了一个比较简单的雏形
绿色正方形水平随机运动
蓝色正方形垂直随机运动
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
import java.math.*;
public class MoveRect extends Frame implements Runnable{
private Rectangle hRect, vRect;
private Image buffer;
private Object o = new Object();
public MoveRect(){
super("MoveRect");
hRect = new Rectangle(50,0,50,50);//水平随机运动的正方形
vRect = new Rectangle(0,50,50,50);//垂直随机运动的正方形
setUndecorated(true);
setLocation(500,200);
setSize(400,400);
setVisible(true);
addWindowListener(new WindowAdapter(){
public void windowClosing(WindowEvent e){
System.exit(0);
}
});
}
//启动循环绘制(使正方形一直循环的运动)
public void circleDraw(){
}
//绘制正方形的状态
public void drawRect(Graphics g,Rectangle r){
g.drawRect(r.x, r.y, r.width, r.height);
}
//双缓冲机制(主要解决闪屏)
public void update(Graphics g){
buffer = createImage(getSize().width, getSize().height);
if(buffer != null){
Graphics g2 = buffer.getGraphics();
paint(g2);
g2.dispose();
g.drawImage(buffer, 0, 0, this);
}
else{
paint(g);
}
}
public void paint(Graphics g){
g.setColor(Color.GREEN);
drawRect(g,hRect);
g.setColor(Color.BLUE);
drawRect(g,vRect);
hRect.x = (int)(Math.random()*351);
vRect.y = (int)(Math.random()*351);
}
public void run(){
while(true){
stop();
rePaint();
}
}
//同步方法rePaint
public synchronized void rePaint(){
repaint();
}
//同步方法stop
public synchronized void stop(){
if(hRect.x <= 50 && vRect.y <= 50){
try {
Thread.sleep(500);
}
catch (Exception ex) {
ex.printStackTrace();
}
}
}
public static void main(String[] args){
new Thread(new MoveRect()).start();
}
}
希望能帮助你哈
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询