《java小球问题代码 (2)》由会员分享,可在线阅读,更多相关《java小球问题代码 (2)(4页珍藏版)》请在金锄头文库上搜索。
1、package Ball;import java.awt.geom.Ellipse2D;import java.awt.geom.Rectangle2D;/* * author zhoduapeg* */public class Ball private static final int XSIZE = 15;private static final int YSIZE = 15;private double x = 0;private double y = 0;private double dx = 1;private double dy = 1;public void move(Recta
2、ngle2D bounds) x+= dx;y+=dy;if(x = bounds.getMaxX() x = bounds.getMaxX()-XSIZE;dx = -dx;if(y = bounds.getMaxY() x = bounds.getMaxY()-YSIZE;dy = -dy;public Ellipse2D getShape() return new Ellipse2D.Double(x, y, XSIZE, YSIZE);*package Ball;import java.awt.Graphics;import java.awt.Graphics2D;import jav
3、a.awt.Shape;import java.util.ArrayList;import javax.swing.JFrame;/* * author zhoduapeng*The comparator that draw balls*/public class BallComponent extends JFrameOverridepublic void paintComponents(Graphics g) super.paintComponents(g);Graphics2D g2 = (Graphics2D)g;for(Ball b : balls) g2.fill( b.getSh
4、ape();private ArrayList balls = new ArrayList();public void add(Ball b) balls.add(b);*package Ball;import java.awt.BorderLayout;import java.awt.Container;import java.awt.EventQueue;import java.awt.event.ActionEvent;import java.awt.event.ActionListener;import java.util.Timer;import java.util.TimerTas
5、k;import javax.swing.JButton;import javax.swing.JFrame;import javax.swing.JPanel;public class Bounce /* shows an animated bouncing ball* * param args* author zhoudapeng*/public static void main(String args) EventQueue.invokeLater(new Runnable() / 导致 runnable 的 run 方法在 the/ system EventQueue 的指派线程中被调
6、用。Overridepublic void run() JFrame frame = new BounceFrame();frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);frame.setVisible(true););/* the frame with ball component and buttons*/class BounceFrame extends JFrame private BallComponent comp;public static final int Defult_WIDTH = 450;public stati
7、c final int Defult_HEIGHT = 350;public static final int steps = 1000;public static final int delay = 3;public BounceFrame() this.setSize(Defult_WIDTH, Defult_HEIGHT);this.setTitle(bounce);comp = new BallComponent();add(comp, BorderLayout.CENTER);JPanel buttonPanel = new JPanel();addButton(buttonPane
8、l, start, new ActionListener() Overridepublic void actionPerformed(ActionEvent e) addBall(););addButton(buttonPanel, stop, new ActionListener() Overridepublic void actionPerformed(ActionEvent e) System.exit(0););this.add(buttonPanel, BorderLayout.SOUTH);public void addButton(Container c, String titl
9、e, ActionListener listener) JButton jb = new JButton(title);c.add(jb);jb.addActionListener(listener);/* add a bounce ball to the panel and makes it bounces 1000 times* * throws InterruptedException*/public void addBall() Ball ball = new Ball();comp.add(ball);for (int i = 1; i steps; i+) / ball.move(comp.getBounds();comp.paint(getGraphics();try Thread.sleep(delay); catch (InterruptedException e) / TODO Auto-generated catch blocke.printStackTrace();