import java.awt.*;
import javax.swing.*;
public class ball {
public static void main(String args[]){
JFrame w = new JFrame();
w.setSize(1000, 800);
MyPanel mp = new MyPanel();
mp.My();
Thread t = new Thread(mp);
t.start();
w.add(mp);
w.show();
}
}
class MyPanel extends JPanel implements Runnable{
int x[] = new int[4];
int y[] = new int[4];
int a[] = new int[4];
public void My(){
for(int i = 0;i<4;i++){
x[i] = (int)(Math.random()*1000);
y[i] = (int)(Math.random()*800);
a[i] = (int)(Math.random()*4);
}
}
public void paint(Graphics g){
super.paint(g);
for(int i = 0;i<4;i++){
g.fillOval(x[i], y[i], 20, 20);
}
}
public void run(){
for(int i = 0;i<4;i++)
while(true){
try{
if(a[i]==0){
x[i]++;
y[i]++;
}
if(a[i]==1){
x[i]--;
y[i]++;
}
if(a[i]==2){
x[i]--;
y[i]--;
}
if(a[i]==3){
x[i]++;
y[i]--;
}
if(y[i]>750){
if(a[i]==1){
a[i]=2;
}else{
a[i]=3;
}
}
if(x[i]<0){
if(a[i]==2){
a[i]=3;
}else{
a[i]=0;
}
}
if(y[i]<0){
if(a[i]==3){
a[i]=0;
}else{
a[i]=1;
}
}
if(x[i]>970){
if(a[i]==0){
a[i]=1;
}else{
a[i]=2;
}
}
Thread.sleep(5);
}catch(Exception e){}
repaint();
}
}
}
运行为什么只有一个球能动
import javax.swing.*;
public class ball {
public static void main(String args[]){
JFrame w = new JFrame();
w.setSize(1000, 800);
MyPanel mp = new MyPanel();
mp.My();
Thread t = new Thread(mp);
t.start();
w.add(mp);
w.show();
}
}
class MyPanel extends JPanel implements Runnable{
int x[] = new int[4];
int y[] = new int[4];
int a[] = new int[4];
public void My(){
for(int i = 0;i<4;i++){
x[i] = (int)(Math.random()*1000);
y[i] = (int)(Math.random()*800);
a[i] = (int)(Math.random()*4);
}
}
public void paint(Graphics g){
super.paint(g);
for(int i = 0;i<4;i++){
g.fillOval(x[i], y[i], 20, 20);
}
}
public void run(){
for(int i = 0;i<4;i++)
while(true){
try{
if(a[i]==0){
x[i]++;
y[i]++;
}
if(a[i]==1){
x[i]--;
y[i]++;
}
if(a[i]==2){
x[i]--;
y[i]--;
}
if(a[i]==3){
x[i]++;
y[i]--;
}
if(y[i]>750){
if(a[i]==1){
a[i]=2;
}else{
a[i]=3;
}
}
if(x[i]<0){
if(a[i]==2){
a[i]=3;
}else{
a[i]=0;
}
}
if(y[i]<0){
if(a[i]==3){
a[i]=0;
}else{
a[i]=1;
}
}
if(x[i]>970){
if(a[i]==0){
a[i]=1;
}else{
a[i]=2;
}
}
Thread.sleep(5);
}catch(Exception e){}
repaint();
}
}
}
运行为什么只有一个球能动