该楼层疑似违规已被系统折叠 隐藏此楼查看此楼
效果实现了,代码你自己优化,太不规范了
package com.test;
import java.awt.Color;
import java.awt.Frame;
import java.awt.Graphics;
import java.awt.Panel;
import java.util.Random;
import javax.swing.JFrame;
public class MainTest {
public static void main(String[] args) {
Frame f = new JFrame();
f.setSize(300, 400);
Mypanel b = new Mypanel();
f.add(b);
Thread t = new Thread(b);
t.start();
f.setVisible(true);
}
}
class Mypanel extends Panel implements Runnable {
int x = 30;
int y = 30;
int z = 0;
int rjb = 0;
Color color;
public void updateBallColor() {
Random rand = new Random();
color = new Color(rand.nextInt(256),rand.nextInt(256),rand.nextInt(256));
}
public void paint(Graphics g) {
g.setColor(color);
g.fillOval(x, y, 20, 20);
}
public void run() {
while (true) {
if (z == 0) {
x++;
y++;
}
if (z == 1) {
x--;
y++;
}
if (z == 2) {
x--;
y--;
}
if (z == 3) {
x++;
y--;
}
if (x > 263) {
if (z == 0) {
z = 1;
} else {
z = 2;
}
updateBallColor();
}
if (y > 342) {
if (z == 1) {
z = 2;
} else {
z = 3;
}
updateBallColor();
}
if (x < 0) {
if (z == 2) {
z = 3;
} else {
z = 0;
}
updateBallColor();
}
if (y < 0) {
if (z == 3) {
z = 0;
} else {
z = 1;
}
updateBallColor();
}
repaint();
try {
Thread.sleep(5);
} catch (Exception e) {
}
}
}
}