上一节实现了滚雪球的代码,这一节实现下雪球的代码,简单考虑,制造一个循环,产生30个随机数,代码如下:
import java.awt.Color;
import java.awt.Frame;
import java.awt.Graphics;
import java.awt.Panel;
public class SnowBall {
public static void main(String[] args) {
Frame frame=new Frame();
frame.setBackground(Color.BLACK);
frame.setSize(1024, 768);
MyPanel myPanel=new MyPanel();
frame.add(myPanel);
Thread thread=new Thread(myPanel);
thread.start();
frame.show();
}
}
class MyPanel extends Panel implements Runnable{
int y=0;
@Override
public void paint(Graphics g) {
g.setColor(Color.WHITE);
for (int i = 0; i < 30; i++) {
y=(int)(Math.random()*768);
int x=(int)(Math.random()*1024);
g.fillOval(x, y, 20, 20);
}
}
@Override
public void run() {
for (int i = 0; i < 30; i++) {
while (true) {
y++;
if(y>768){
y=0;
}
repaint();
try {
Thread.sleep(700);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
}
这时运行实例:
这时发现不是下雪球,而是满屏幕乱散。思考一下问什么,原因是每次paint都会在全新的300个位置画雪球。因此我们必须要实现准备30个随机坐标。
代码如下:
import java.awt.Color;
import java.awt.Frame;
import java.awt.Graphics;
import java.awt.Panel;
public class SnowBall {
public static void main(String[] args) {
Frame frame = new Frame();
frame.setBackground(Color.BLACK);
frame.setSize(1024, 768);
MyPanel myPanel = new MyPanel();
frame.add(myPanel);
Thread thread = new Thread(myPanel);
thread.start();
frame.show();
}
}
class MyPanel extends Panel implements Runnable {
int x[] = new int[30];
int y[] = new int[30];
public MyPanel() {
for (int i = 0; i < 30; i++)
{
x[i] = (int) (Math.random() * 1024);
y[i] = (int) (Math.random() * 768);
}
}
@Override
public void paint(Graphics g) {
g.setColor(Color.WHITE);
for (int i = 0; i < x.length; i++) {
g.fillOval(x[i], y[i], 20, 20);
}
}
@Override
public void run() {
while (true) {
for (int i = 0; i < 30; i++) {
y[i]++;
if (y[i] > 768) {
y[i] = 0;
}
try {
Thread.sleep(3);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
repaint();
}
}
}
运行如下:
这时就是不乱了。还有其他创意可以加入,读者自行设计。
标签:Java,上机,int,frame,30,import,new,public,雪球 From: https://blog.51cto.com/u_15866446/5844865