0

So I'm in my first programming class this quarter and I decided to test what I've learned so far and create my very first game! I completed a purely text based game that puts the user against a computer and attacks defends and evades trying to bring the computers life points down to zero.

I wanted to add some sort of visual animation to the game and i cant seem to find a way to make it so that when the user presses a button on the buttonPanel a specific animation will appear.

The goal is to have a default image of the human and computer standing on a battlefield, then when you press a button new frames will display in sequence making an animation, then i want the default image to display again.

I built a BattleGame class and then a RolePlay class that extends BattleGame.

My Question is: Why wont the images come up at all when i run the program. I tried putting the animation() method inside the attack() method and it still didn't work. The animation isn't coming up at all. I know the problem is inside the animation() method. I just don't know why it wont work.

http://i1209.photobucket.com/albums/cc400/squaredcorn/program_zps23d42f2d.png

The first chunk of code is the animation method I'm trying to create. The rest is the entire BattleGame class. "the animation method is just after actionPerformed

Thanks for any help, I know its a lot of code but I'm really desperate and I'm not sure why it doesn't work :'(

    public Image[] frames = new Image[3];
       public void animation() {
          try {
             frames[0] = ImageIO.read(new File("1.png"));
             frames[1] = ImageIO.read(new File("2.png"));
             frames[2] = ImageIO.read(new File("3.png"));

          } 
          catch (Exception e) { }  

          JPanel gui = new JPanel(new BorderLayout());

          final JLabel attackAnimation = new JLabel(new ImageIcon(frames[0]));
          gui.add(attackAnimation, BorderLayout.EAST);

          int index = 0; 
          if(index < frames.length){
             index++;
             if(index > frames.length) index = 0;
          }   
          attackAnimation.setIcon(new ImageIcon(frames[index]));

          final Timer timer = new Timer(200, this);

          if(index >= 0){
             timer.start();
          }
          else {
             timer.stop();
          }

       }


import java.awt.Color;
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.text.*;

import java.io.*;
import javax.imageio.ImageIO;

public abstract class BattleGame extends JFrame implements ActionListener
{   
   private JTextField[] fields;
   public JTextArea display;
   private JButton attackBtn;
   private JButton blockBtn;
   private JButton dodgeBtn;
   private JButton fleeBtn;

   /* Helper objects for simplifying common tasks */
   public StringBuilder output = new StringBuilder(128);

   public NumberFormat decimalFormat = new DecimalFormat("0.00");   
   public NumberFormat currencyFormat = NumberFormat.getCurrencyInstance();
   public NumberFormat percentFormat = NumberFormat.getPercentInstance();
   public DateFormat dateFormat = DateFormat.getDateInstance();   

   // constructor
   public BattleGame(String... prompts)
   {
      super("Display Frame");
      setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
      setSize(1000,750);

      // store the number of prompts in a simple short variable
      int rows = prompts.length;

      JPanel entryPanel = new JPanel();
      entryPanel.setLayout(new GridLayout(rows,2,4,4));

      // create a new empty array of JTextFields where the number of
      // elements is set to the number of rows
      fields = new JTextField[rows];

      // Use a standard for loop to build the entryPanel 
      for(int i = 0; i < rows; i++)
      {
         fields[i] = new JTextField(10);
         entryPanel.add(new JLabel(prompts[i] + ":", JLabel.RIGHT));
         entryPanel.add(fields[i]);
      }

      display = new JTextArea(7,50);
      JScrollPane displayPane = new JScrollPane(display);

      ImageIcon attackPicture = new ImageIcon("AttackButton.jpg");//start attack button with Icon
      attackBtn = new JButton(attackPicture);//end attack Button with Icon

      ImageIcon blockPicture = new ImageIcon("BlockButton.jpg");//start block button with Icon
      blockBtn = new JButton(blockPicture);//end block button with Icon

      ImageIcon dodgePicture = new ImageIcon("EvadeButton.jpg");//start dodge button with Icon
      dodgeBtn = new JButton(dodgePicture);//end dodge button with Icon

      ImageIcon fleePicture = new ImageIcon("FleeButton.jpg");//start flee button with Icon
      fleeBtn = new JButton(fleePicture);//end flee button with Icon


      JLabel animation = new JLabel();

      attackBtn.addActionListener(this);
      blockBtn.addActionListener(this);
      dodgeBtn.addActionListener(this);
      fleeBtn.addActionListener(this);

      JPanel buttonPanel = new JPanel();
      buttonPanel.add(attackBtn);
      buttonPanel.add(blockBtn);
      buttonPanel.add(dodgeBtn);
      buttonPanel.add(fleeBtn);

      add(animation, BorderLayout.EAST);
      add(entryPanel, BorderLayout.NORTH);
      add(displayPane, BorderLayout.WEST);
      add(buttonPanel, BorderLayout.SOUTH);

      //setVisible(true); 
   } // end constructor

   public void actionPerformed(ActionEvent event)
   {
      if (event.getSource() == attackBtn)
      {
         // make sure all run-time errors are caught and handled by putting
         // the run method in a try-catch block.
         try {
            attack();
            display.setText(output.toString());
         } 
         catch (Exception error) {
            display.setText("There is a problem " + error.getMessage());
         }
      }
      if (event.getSource() == blockBtn)
      {
         // make sure all run-time errors are caught and handled by putting
         // the run method in a try-catch block.
         try {
            block();
            display.setText(output.toString());
         } 
         catch (Exception error) {
            display.setText("There is a problem " + error.getMessage());
         }
      }
      if (event.getSource() == dodgeBtn)
      {
         // make sure all run-time errors are caught and handled by putting
         // the run method in a try-catch block.
         try {
            dodge();
            display.setText(output.toString());
         } 
         catch (Exception error) {
            display.setText("There is a problem " + error.getMessage());
         }
      }
      if (event.getSource() == fleeBtn)
      {
         // make sure all run-time errors are caught and handled by putting
         // the run method in a try-catch block.
         try {
            flee();
            display.setText(output.toString());
         } 
         catch (Exception error) {
            display.setText("There is a problem " + error.getMessage());
         }
      }  


   } // end actionPerformed()

   public void clearOutput() {
      getOutput().setLength(0);
      getDisplay().setText("");      
   }







   ////////////////////////////////////////////////////
   public Image[] frames = new Image[3];
   public void animation() {
      try {
         frames[0] = ImageIO.read(new File("1.png"));
         frames[1] = ImageIO.read(new File("2.png"));
         frames[2] = ImageIO.read(new File("3.png"));

      } 
      catch (Exception e) { }  

      JPanel gui = new JPanel(new BorderLayout());

      final JLabel attackAnimation = new JLabel(new ImageIcon(frames[0]));
      gui.add(attackAnimation, BorderLayout.EAST);

      int index = 0; 
      if(index < frames.length){
         index++;
         if(index > frames.length) index = 0;
      }   
      attackAnimation.setIcon(new ImageIcon(frames[index]));

      final Timer timer = new Timer(200, this);

      if(index >= 0){
         timer.start();
      }
      else {
         timer.stop();
      }

   }

   ////////////////////////////////////////////////////








   public JTextArea getDisplay() {
      return display;
   }
   /** @return   output object */    
   public StringBuilder getOutput() {
      return output;
   }

   // set method for fields
   public void setField(int index, String text)
   {
      fields[index].setText(text);
   }

   // get method for fields
   public String getField(int index)
   {
      // get the text from the field and return it to the caller
      return fields[index].getText();
   }

   public int getFieldAsInt(int index)
   {
      // convert the text to an int and return it to the caller
      return Integer.parseInt(getField(index));
   } 

   public double getFieldAsDouble(int index)
   {
      // convert text to a double and return it to the caller
      return Double.parseDouble(getField(index));
   }

   /**
   * This method builds the output string that will eventually be displayed
   * in the text area as the final problem solution report.
   * @param value   value will be appended to the StringBuilder object with a
   * new line character at the end.
   */
   public void addOutput(String value) 
   {
      output.append(value);
      output.append("\n");
   }  

   // a python-like print method that takes any kind of object
   public void print(Object obj)
   {
      System.out.println(obj);
   }

   // run must be implemented in all subclasses
   public abstract void attack(); 
   public abstract void block();
   public abstract void dodge();
   public abstract void flee();

} // end class
Peter Badida
  • 11,310
  • 10
  • 44
  • 90
  • 1
    Where's the `actionPerformed` method? – MadProgrammer Feb 22 '14 at 05:49
  • let me know if you guys need any more info ill be monitoring this post for the next 2 hours – SquaredCorn Feb 22 '14 at 05:51
  • 1
    You haven't actually _asked_ a question, like why something doesn't work. – Paul Samsotha Feb 22 '14 at 05:57
  • 1) For better help sooner, post a [MCTaRE](http://stackoverflow.com/help/mcve) (Minimal Complete Tested and Readable Example). 2) One way to get image(s) for an example is to hot-link to the images seen in [this answer](http://stackoverflow.com/a/19209651/418556). – Andrew Thompson Feb 22 '14 at 06:13
  • Where are your image files located in your file structure? – Paul Samsotha Feb 22 '14 at 06:17
  • 1
    `frames[0] = ImageIO.read(new File("1.png"));` By the time of deployment, those resources will likely become an [tag:embedded-resource]. That being the case, the resource must be accessed by `URL` instead of `File`. See the [info page](http://stackoverflow.com/tags/embedded-resource/info) for the tag, for a way to form an `URL`. – Andrew Thompson Feb 22 '14 at 06:18
  • 1
    General tip: Change code of the form `catch (Exception e) { ..` to `catch (Exception e) { e.printStackTrace(); // very informative! ..` – Andrew Thompson Feb 22 '14 at 06:20
  • @AndrewThompson make those two points an answer. I would bet those two things are the problem... the image location at least. – Paul Samsotha Feb 22 '14 at 06:22
  • Where is the `gui` panel with the image labels ever added? – Paul Samsotha Feb 22 '14 at 06:27
  • the pictures 1,2,and 3 are in the same directory as the class so i thought i didnt need to use a directory, how would i use URL instead of File? When i try swapping File for URL it i get an error – SquaredCorn Feb 22 '14 at 06:27
  • *"i get an error"* Always copy/paste error & exception output. – Andrew Thompson Feb 22 '14 at 06:29
  • _"the pictures 1,2,and 3 are in the same directory as the class"_. Use `getClass().getResource("myimage.jpg")` for the URL, as noted in links from AndrewThompson's answer – Paul Samsotha Feb 22 '14 at 06:30
  • I just tried this format in the code and im still getting errors, any thoughts on why else it wouldn't be finding the image?? - URL frames[0] = this.getClass().getResource("C:/Users/Connor/jGrasp/1.png"); – SquaredCorn Feb 22 '14 at 06:58

2 Answers2

1
frames[0] = ImageIO.read(new File("1.png")); 

By the time of deployment, those resources will likely become an embedded-resource. That being the case, the resource must be accessed by URL instead of File. See the info page for the tag, for a way to form an URL.

General tip: Change code of the form:

catch (Exception e) { 
    .. 

to:

catch (Exception e) { 
    e.printStackTrace(); // very informative! 
    ..
Community
  • 1
  • 1
Andrew Thompson
  • 168,117
  • 40
  • 217
  • 433
1

I just tried this format in the code and im still getting errors, any thoughts on why else it wouldn't be finding the image?? - URL frames[0] = this.getClass().getResource("C:/Users/Connor/jGrasp/1.png");

Keeping this short, use

Image img = ImageIO.read(getClass().getResource("1.png"));

You already said your images are in the same package as the class.. keep them there.

ProjectRoot
         src
            mypackage
                   MyClass.java
                   1.png

Also note, in your animation method, you create a JPanel gui with the image label being added to it, but you never add the gui to anything.

Paul Samsotha
  • 205,037
  • 37
  • 486
  • 720