您的位置:首页 > 编程语言 > Java开发

【JAVA】简单动态交互程序——弹球

2011-05-27 16:21 288 查看
import java.awt.Frame;
import java.awt.Graphics;
import java.awt.Image;
import java.awt.Point;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import javax.swing.JApplet;
import javax.swing.JPanel;
import java.awt.Color;
import java.util.ArrayList;
import java.util.List;
import java.awt.event.*;

public class BounceBall extends Frame {

public static final int BOARD_WIDTH = 540;
public static final int BOARD_HEIGHT = 570;
List <Ball> balls = new ArrayList<Ball>();
Image offScreenImage = null;      //双缓冲用的

class Ball {
int direction = 0;
int x = 0;
int y = 0;
Color color;
public static final int BALLSIZE = 20;
public  final  Color[] colors={Color.black,Color.blue,Color.cyan,Color.green,Color.orange,Color.pink,Color.red};
public void drawBall(Graphics g) {
if(direction == 1) g.clearRect(x, y-5, 20, 20);
else g.clearRect(x,y+5,20,20);
g.setColor(color);
g.fillOval(x,y,20,20);
}
public Ball(int x, int y, int ballcount) {
this.x = x;
this.y = y;
this.direction = 1 ;
this.color = colors[ballcount%7];
}
}
public void paint(Graphics g) {
for(int i=0;i<balls.size();i++){
Ball b = null;
b=balls.get(i);
b.drawBall(g);
}
}

//    双缓冲用的
@Override
public void update(Graphics g)  {
if(offScreenImage == null){
offScreenImage = this.createImage(BOARD_WIDTH, BOARD_HEIGHT);
}
Graphics gOffScreen = offScreenImage.getGraphics();
Color c  = gOffScreen.getColor();
gOffScreen.setColor(Color.LIGHT_GRAY);
gOffScreen.fillRect(0, 0, BOARD_WIDTH, BOARD_HEIGHT);
gOffScreen.setColor(c);
paint(gOffScreen);
g.drawImage(offScreenImage, 0, 0, null);
for(int i=0;i<balls.size();i++){
if(balls.get(i).y> BOARD_HEIGHT-Ball.BALLSIZE) balls.get(i).direction=0;
if(balls.get(i).y< Ball.BALLSIZE)  balls.get(i).direction=1;
if(balls.get(i).direction==1) balls.get(i).y+=5;
if(balls.get(i).direction==0) balls.get(i).y-=5;
}
}
//    重画
private class PaintThread implements Runnable {

public void run() {
try {
while(true){
repaint();
Thread.sleep(50);
}
}catch (InterruptedException e) {
e.printStackTrace();
}
}
}

private class MouseMonitor extends MouseAdapter{
public void mouseClicked(MouseEvent e) {
int x = e.getX();
int y = e.getY();
Ball b = new Ball(x,y,balls.size());
balls.add(b);
}
}

public void launchFrame() throws Exception{

//界面初始化
this.setLocation(100, 50);
this.setSize(BOARD_WIDTH, BOARD_HEIGHT);
this.setResizable(false);
this.setBackground(Color.LIGHT_GRAY);
setVisible(true);

//重画
new Thread(new PaintThread()).start();

this.addMouseListener(new MouseMonitor());

this.addWindowListener(new WindowAdapter(){
public void windowClosing (WindowEvent e){
System.exit(0);
}
});

}
public static void main(String[] args)throws Exception {
new BounceBall().launchFrame();
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: