[java]代码库
package day06;
import javax.swing.JFrame;
public class BallFrame {
public BallFrame(){
JFrame frame = new JFrame();
frame.setTitle("弹球游戏");
frame.setDefaultCloseOperation(frame.EXIT_ON_CLOSE);
frame.setBounds(100,200,800,600);
frame.setVisible(true);
BallPanel bp = new BallPanel();
frame.add(bp);
frame.setVisible(true);
}
public static void main(String[] args) {
new BallFrame();
}
}
package day06;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.event.MouseEvent;
import java.awt.event.MouseMotionListener;
import javax.swing.JPanel;
public class BallPanel extends JPanel implements MouseMotionListener {
final static int RIIGHT_DOWN = 0;
final static int LEFT_DOWN=1;
final static int LEFT_UP =2;
final static int RIGHT_UP=3;
int f=0;
int speed = 10;
int bx=0;
int by=0;
int dx=100;
int dy=400;
public BallPanel(){
move();
addMouseMotionListener(this);
}
public void paint(Graphics g){
super.paint(g);
setBackground(Color.black);
g.setColor(Color.yellow);
g.fillOval(bx, by,20, 20);
g.setColor(Color.blue);
g.fillRect(dx, dy, 100, 20);
}
public void move(){
new Thread(){
public void run(){
while(true){
if(f==0){
bx+=speed;
by+=speed;
}
if(f==1){
bx-=speed;
by+=speed;
}
if(f==2){
bx-=speed;
by-=speed;
}
if(f==3){
bx+=speed;
by-=speed;
}
if(bx>800-20){
if(f==0){
f=1;
}else{
f=2;
}
}
if(by>600-20){
if(f==1){
f=2;
}else{
f=3;
}
}
if(bx<0){
if(f==1){
f=0;
}else{
f=3;
}
}
if(by<0){
if(f==2){
f=1;
}else{
f=0;
}
}
if (by >= 400 - 20) {
if (bx >= dx && bx <= dx + 100) {
speed++;
} else {
Thread.currentThread().stop();
}
if (speed >= 20)
{
speed = 20;
}
if (f == 1) {
f = 2;
} else {
f = 3;
}
}
repaint();
try {
Thread.sleep(100);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}.start();
}
@Override
public void mouseDragged(MouseEvent e) {
// TODO Auto-generated method stub
}
@Override
public void mouseMoved(MouseEvent e) {
// TODO Auto-generated method stub
dx = e.getX()-100/2;
}
}