boxglue

Bouncing Images Example

Apr 27th, 2020
110
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 5.08 KB | None | 0 0
  1. package bouncer;
  2.  
  3. /* NOTE: requires MyImage.java */
  4.  
  5. import java.awt.BorderLayout;
  6. import java.awt.Color;
  7. import java.awt.Dimension;
  8. import java.awt.Graphics;
  9. import java.awt.event.ActionEvent;
  10. import java.awt.event.ActionListener;
  11. import java.util.ArrayList;
  12.  
  13. import javax.swing.JButton;
  14. import javax.swing.JFrame;
  15. import javax.swing.JPanel;
  16.  
  17.  
  18.  
  19. public class BouncingImages extends JFrame implements ActionListener {
  20.  
  21.     public static void main(String[] args) {
  22.         new BouncingImages();
  23.     }
  24.  
  25.    
  26.     /* These are the width and height of the DrawingPanel NOT the whole JFrame.
  27.     Bouncing off walls will not work properly if it's the JFrame size */
  28.     static final int WINW = 1000;
  29.     static final int WINH = 800;
  30.  
  31.     JPanel buttonPanel = new JPanel();
  32.     AnimationPanel animationPanel;
  33.     ArrayList<MyImage> imageList = new ArrayList<MyImage>();
  34.     AnimationThread thread;
  35.     private volatile boolean stopRequested = false; //maybe should use AtomicBoolean
  36.  
  37.     BouncingImages() {
  38.  
  39.         //set up button panel
  40.         JButton btnStart = new JButton("Start");
  41.         JButton btnStop  = new JButton("Stop");
  42.         JButton btnExit  = new JButton("Exit");
  43.         btnStart.addActionListener(this);
  44.         btnStop.addActionListener(this);
  45.         btnExit.addActionListener(this);
  46.         buttonPanel.add(btnStart);
  47.         buttonPanel.add(btnStop);
  48.         buttonPanel.add(btnExit);
  49.  
  50.         animationPanel = new AnimationPanel();
  51.  
  52.         //setup JFrame
  53.         //this.setExtendedState(JFrame.MAXIMIZED_BOTH); //If we use this, then we need to determine the dimensions of the JPanel before we start drawing
  54.         // this.setUndecorated(true);
  55.         this.add(buttonPanel, BorderLayout.SOUTH);
  56.         this.add(animationPanel);
  57.         this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
  58.         this.pack(); //since the JPanel is controlling the size, we need pack() here.
  59.         this.setLocationRelativeTo(null);   //after pack();
  60.         this.setVisible(true);
  61.     }
  62.  
  63.     void startAnimation() {
  64.         //this doesn't restart the thread if it terminates
  65.         if (thread == null) {
  66.             thread = new AnimationThread ();
  67.             stopRequested = false;
  68.             thread.start();        
  69.         }
  70.         //System.out.println("thread is " + thread.toString());
  71.  
  72.         //this will "restart" the thread!
  73.         if (thread.getThreadGroup() == null) {
  74.             thread = new AnimationThread ();
  75.             stopRequested = false;
  76.             thread.start();
  77.         }
  78.  
  79.     }
  80.  
  81.     //two different versions here as I was testing how to stop threads properly
  82.     void stopAnimation1(){
  83.         stopRequested = true;      
  84.     }
  85.  
  86.     void stopAnimation2(){     
  87.         thread.interrupt();
  88.         //System.out.println(thread.isInterrupted());
  89.     }
  90.  
  91.     void addImage()  {     
  92.         imageList.add(new MyImage("fish.jpeg"));
  93.     }
  94.  
  95.     void moveAllImages() {
  96.         for (MyImage image : imageList) {                  
  97.             image.moveImage();
  98.         }
  99.     }
  100.  
  101.  
  102.     //ActionListener for Buttons
  103.     @Override
  104.     public void actionPerformed(ActionEvent e) {
  105.         if (e.getActionCommand().equals("Start")) {
  106.             addImage();
  107.             startAnimation();
  108.         }
  109.         if (e.getActionCommand().equals("Stop")) {
  110.             stopAnimation2();          
  111.         }
  112.         if (e.getActionCommand().equals("Exit")) {
  113.             System.exit(0);        
  114.         }
  115.     }
  116.  
  117.     //This class does drawing graphics and nothing else
  118.     class AnimationPanel extends JPanel {
  119.  
  120.         AnimationPanel() {
  121.             this.setBackground(Color.BLACK);
  122.             this.setPreferredSize(new Dimension(WINW, WINH));
  123.         }
  124.  
  125.  
  126.         @Override
  127.         public void paintComponent(Graphics g){
  128.             super.paintComponent(g);
  129.             for (MyImage im : imageList) {
  130.                 g.drawImage(im.image, im.x, im.y, im.width, im.height,null);
  131.             }
  132.         }
  133.     }
  134.  
  135.     /* NOTE: I'm not that experienced with threads, preferring to use timers. A Swing Timer would work perfectly for this program
  136.      * Quote: "Starting from Java 5 it is not a good idea to work with Threads directly.
  137.      * You should rather use Executor framework and choose an execution policy depending on your requirements."
  138.      */
  139.     private class AnimationThread extends Thread {
  140.  
  141.         public void run() {
  142.             run2B(); //here we can test different methods
  143.         }
  144.        
  145.         //this version stops the thread using a flag and break. (use stopAnimation1())
  146.         public void run1() {
  147.             while (true) {     
  148.                
  149.                 //everything in the main game loop goes here
  150.                 moveAllImages();
  151.                 //collide_images()
  152.                 animationPanel.repaint();
  153.  
  154.                 try {
  155.                     this.sleep(5);
  156.                 } catch (InterruptedException e) {}
  157.  
  158.                 if(stopRequested) break;
  159.             }
  160.  
  161.         }
  162.  
  163.         //this version stops the thread using an interrupt and break (use stopAnimation2())
  164.         public void run2A() {
  165.             while (true) {
  166.                 moveAllImages();
  167.                 //collide_images()
  168.                 animationPanel.repaint();
  169.  
  170.                 try {
  171.                     this.sleep(5);
  172.                 } catch (InterruptedException e) {     
  173.                     System.out.println("interrupted");
  174.                     break;
  175.                 }              
  176.             }
  177.         }
  178.  
  179.         //this version stops the thread using interrupt only (use stopAnimation2())
  180.         public void run2B() {
  181.             while ( ! thread.isInterrupted() ) {  // or     //while (! Thread.currentThread().isInterrupted() ) {
  182.                 moveAllImages();
  183.                 //collide_images()
  184.                 animationPanel.repaint();
  185.  
  186.                 try {
  187.                     this.sleep(5);
  188.                 } catch (InterruptedException e) {
  189.                     System.out.println("interrupted");
  190.                     thread.interrupt(); //catching the exception seems to clear it.
  191.                 }
  192.             }
  193.         }
  194.     }
  195. }
Add Comment
Please, Sign In to add comment