/** * A Sample Animation with a Restart button * * @author Fr Chris Thiel, OFMCap * Applet version 12 May 2011 * Application Version May 12, 2023 */ import java.awt.event.*; import java.applet.Applet; import java.awt.*; import java.io.IOException; import javax.swing.*; public class Bounce extends JPanel implements ActionListener { //EasySound boing; public static int WIDTH=800; public static int HEIGHT=650; private Timer timer; //Image virtualMem; //Graphics gBuffer; private Ball ball; private Wall top,bottom,left,right; private int appletWidth; private int appletHeight; private int frame; private int lastFrame; private Button myButton; private int count; private EasySound boing; public Bounce() { boing = new EasySound("boing.wav"); boing.play(); ball = new Ball(10); top = new Wall(0,0,800,10); bottom = new Wall(0,590,800,10); left = new Wall(0,10,10,590); right = new Wall(790,10,10,590); appletWidth = getWidth(); appletHeight = getHeight(); frame=0; timer=new Timer(1, this); lastFrame=appletWidth; count=0; myButton= new Button("Do It Again"); //the class is its own button listener myButton.addActionListener (this); add(myButton); } public static void main(String[] args) { Bounce app= new Bounce(); JFrame window = new JFrame("Bounce Example"); window.setSize(WIDTH, HEIGHT); window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); window.getContentPane().add(app); //window.addKeyListener(app); //window.pack(); window.setVisible(true); } public void paintComponent(Graphics g) { //We draw using the object methods of // the graphics buffer, not what is // currently on the screen super.paintComponent(g); g.setColor(Color.white); g.fillRect(0,0,appletWidth,appletHeight); g.setColor(Color.black); g.setColor(Color.black); g.drawString("Frame "+frame, 20,20); g.drawString(count+" bounces", 20, 35); ball.draw(g); top.draw(g); bottom.draw(g); left.draw(g); right.draw(g); //Now we send the result to the screen //g.drawImage(virtualMem,0,0,this); } public void update(Graphics g) { paint(g); //get rid of flicker with this method } /** * ActionListener is an interface and * requires the actionPerformed() method * to be defined..in this case we * look for a restart button being pressed */ public void actionPerformed(ActionEvent e){ Object source = e.getSource(); if (source == timer) { frame++; frame%=100; ball.move(); if (top.touches(ball) || bottom.touches(ball)){ ball.bounceVertical(); //boing.play(); count++; } if (left.touches(ball) || right.touches(ball)){ ball.bounceHorizontal(); //boing.play(); count++; } } else {//restart button pressed frame=0; if (timer.isRunning()) { timer.stop(); myButton.setLabel("Start"); ball.setVisable(false); count=0; } else { timer.start(); myButton.setLabel("Stop"); ball=new Ball(10); ball.setVisable(true); //boing.play(); } } repaint(); } }