编写程序,该程序通过一个发射按钮可以发射一个弹球,该球遇到边界时会自动弹回,在移动固定次数后,该球停止运动。要求每次点击发射按钮都会发射一个弹球,如果点击多次,则多个弹球同时运动。该程序通过另一个结束可以结束程序的运行。参考界面如图所示。
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.event.*;
import java.util.ArrayList;
import java.util.Random;
import java.awt.geom.*;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
//装球的容器
class Box extends JPanel{
private ArrayList<Ball>all=new ArrayList<>();
public void add(Ball tp){
all.add(tp);
}
// 绘制all中所有的球
public void paintComponent(Graphics g){
super.paintComponent(g);
Graphics2D x=(Graphics2D)g;
for(Ball tp:all){
// x.draw(tp.generateball());
x.setColor(tp.getc());
x.fill(tp.generateball());
}
}
}
class Ball{
private int w=20,h=20; //用于绘制椭圆
private int x=0,y=0; //定位球坐标
private int dx=1,dy=1; //坐标增量
private int rx,gx,bx;
public Ball(){
Random rd=new Random();
rx=rd.nextInt(250);gx=rd.nextInt(250);bx=rd.nextInt(250);
w=(int)(Math.random()*20)+20;
h=w;
}
public Color getc(){
return new Color(rx,gx,bx);
}
public void move(int minx,int maxx,int miny,int maxy){
x+=dx;
y+=dy;
//越界处理
Random rd=new Random();
int mdx=rd.nextInt(2)+1;
int mdy=rd.nextInt(2)+1;
if(x+w>maxx){
x=maxx-w;
dx=-mdx; //反方向走
}
if(x-w<minx){
x=minx+w;
dx=mdx;
}
if(y+h>maxy){
y=maxy-h;
dy=-mdy; //反方向走
}
if(y-h<miny){
y=miny+h;
dy=mdy;
}
}
public Ellipse2D generateball(){
return new Ellipse2D.Double(x,y,w,h);
}
}
class ballmove implements Runnable{
private Ball tb;
private Box tbox;
private static final int gap=5;
public ballmove(Ball bx,Box bbx){
tb=bx;
tbox=bbx;
}
public void run(){
try{
while(true){
tb.move(0, tbox.getWidth(), 0, tbox.getHeight());
tbox.repaint();
Thread.sleep(gap);
}
}
catch (Exception e){
e.printStackTrace();
}
}
}
class Mwid extends JFrame{
private Box box=new Box();
private static final int width=600;
private static final int height=500;
public Mwid(){
setSize(width, height);
setTitle("弹球程序");
// setLayout();
JPanel btnbox=new JPanel();
JButton beg=new JButton("开始");
JButton end=new JButton("结束");
add(box);
btnbox.add(beg);
btnbox.add(end);
add(btnbox,BorderLayout.SOUTH);
beg.addActionListener(new handlee(1));
end.addActionListener(new handlee(2));
}
public void addBall(){
Ball nb=new Ball();
box.add(nb);
// Runnable t1=new
Thread t1=new Thread(new ballmove(nb,box));
t1.start();
}
//处理按钮事件
class handlee implements ActionListener{
int type;
handlee(int s){
type=s;
}
public void actionPerformed(ActionEvent e){
if(type==1) addBall();
else System.exit(0);
}
}
}
public class Main{
public static void main(String[] args) {
Mwid mf=new Mwid();
mf.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
mf.setVisible(true);
}
}