黑马程序员技术交流社区
标题:
弹球游戏界面
[打印本页]
作者:
15044393192
时间:
2016-3-31 22:48
标题:
弹球游戏界面
package com.qdmmy6.tanqiu;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.awt.geom.Ellipse2D;
import java.util.ArrayList;
import java.util.Random;
import javax.swing.JPanel;
public class TanQiuPanel extends JPanel {
private ArrayList<Ball> list = new ArrayList<Ball>();
public TanQiuPanel() {
this.setFocusable(true);
this.addKeyListener(new KeyAdapter() {
public void keyPressed(KeyEvent e) {
if(e.getKeyCode() == KeyEvent.VK_ENTER) {
start();
}
}
});
}
private void start() {
Ball ball = new Ball();
list.add(ball);
ball.start();
}
public void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2 = (Graphics2D)g;
for(Ball ball : list) {
ball.paint(g2);
}
}
private class MyRun implements Runnable {
private Ball ball;
public MyRun(Ball ball) {
this.ball = ball;
}
public void run() {
for(int i = 0; i < 500; i++) {
ball.move();
repaint();
try {
Thread.sleep(ball.getS());
} catch(Exception e) {}
}
}
}
private class Ball {
private int size = 20;
private Color[] colors = {Color.RED, Color.GRAY, Color.GREEN, Color.BLUE, Color.BLACK, Color.MAGENTA, Color.YELLOW, Color.ORANGE};
private Color color;
private int s;
int x = 10, y = 10;
private Ellipse2D ell = new Ellipse2D.Double(x, y, 20, 20);
private boolean b1 = true;
private boolean b2 = true;
private Thread th;
public Ball() {
s = rand();
Random r = new Random();
color = colors[r.nextInt(colors.length)];
}
public int getS() {
return s;
}
public int rand() {
Random r = new Random();
int s = r.nextInt(30);
return s + 10;
}
public void start() {
if(th == null) {
th = new Thread(new MyRun(this));
th.start();
}
}
public void paint(Graphics2D g2) {
g2.setPaint(color);
g2.fill(ell);
}
public void move() {
if(b1) {
x += 5;
if(x >= getWidth() - 20) {
b1 = false;
}
} else {
x -= 5;
if(x <= 0) {
b1 = true;
}
}
if(b2) {
y += 5;
if(y >= getHeight() - 20) {
b2 = false;
}
} else {
y -= 5;
if(y <= 0) {
b2 = true;
}
}
ell.setFrame(x, y, 20, 20);
}
}
}
欢迎光临 黑马程序员技术交流社区 (http://bbs.itheima.com/)
黑马程序员IT技术论坛 X3.2