Fun little program, Pinball ......... ........
Importjava.awt.*;Importjavax.swing.*;Importjava.awt.event.*;Importjavax.swing.event.*; Public classBallscanvasextendsCanvasImplementsactionlistener,focuslistener{PrivateBall balls[]; PrivateTimer timer;//Timer Private Static classball{intx, y; Color color; BooleanUp,left; Ball (intXintY,color Color) { This. x=x; This. y=y; This. color=color; } } PublicBallscanvas (Color color[],intDelay) {//specify color, delay This. balls=NewBall[color.length]; for(intI=0,x=40;i<color.length;i++,x+=40) Balls[i]=NewBall (X,x,color[i]); This. Addfocuslistener ( This); Timer=NewTimer (Delay, This); Timer.start ();//Timer Start } Public voidSetdelay (intdelay1) {Timer.setdelay (delay1); } Public voidPaint (Graphics g) { for(inti=0;i<balls.length;i++) {g.setcolor (balls[i].color); balls[i].x=balls[i].left?balls[i].x-10:balls[i].x+10; if(balls[i].x<=0| | balls[i].x>= This. GetWidth ())//to the horizontal to change directionballs[i].left=!Balls[i].left; Balls[i].y=balls[i].up?balls[i].y-10:balls[i].y+10; if(balls[i].y<=0| | balls[i].y>= This. GetHeight ())//change direction to vertical edgeballs[i].up=!Balls[i].up; G.filloval (balls[i].x, BALLS[I].Y,20, 20); }} @Override Public voidfocusgained (focusevent e) {//TODO auto-generated Method StubTimer.stop (); } @Override Public voidFocuslost (focusevent e) {//TODO auto-generated Method StubTimer.restart (); } @Override Public voidactionperformed (ActionEvent e) {//TODO auto-generated Method Stubrepaint (); }}classBallsjframeextendsJFrameImplementschangelistener{ PublicBallscanvas Ball; PrivateJSpinner spinner; PublicBallsjframe () {Super("Bouncing Ball"); This. SetBounds (300,200, 480, 360); This. Setdefaultcloseoperation (Exit_on_close); Color colors[]={Color.red,color.green,color.blue,color.magenta,color.cyan}; Ball=NewBallscanvas (colors,100); This. Getcontentpane (). Add (ball); JPanel Panel=NewJPanel (); This. Getcontentpane (). Add (Panel, "South"); Panel.add (NewJLabel ("Delay")); Spinner=NewJSpinner (); Spinner.setvalue (100); Panel.add (spinner); Spinner.addchangelistener ( This); This. setvisible (true); } @Override Public voidstatechanged (ChangeEvent e) {//TODO auto-generated Method StubBall.setdelay (Integer.parseint ("" +Spinner.getvalue ())); } Public Static voidMain (string[] args) {NewBallsjframe (); }}
Java Learning diary-----------------------------Bouncing Balls