在JFrame中创建基本动画

时间:2014-02-22 05:47:09

标签: java swing animation timer jframe

所以我在本季度的第一个编程课程中,我决定测试到目前为止学到的东西并创建我的第一个游戏!我完成了一个纯粹基于文本的游戏,让用户对抗计算机,攻击防御和逃避试图将计算机生命点降低到零。

我想在游戏中添加某种视觉动画,我似乎无法找到一种方法来制作它,以便当用户按下buttonPanel上的按钮时,会出现一个特定的动画。

目标是让人和计算机的默认图像站在战场上,然后当你按下一个按钮时,新的帧将依次显示动画,然后我希望再次显示默认图像。

我构建了一个BattleGame类,然后是一个扩展BattleGame的RolePlay类。

  

我的问题是:为什么我运行程序时根本不会出现图像。我尝试将animation()方法放在attack()方法中,但仍然无法正常工作。动画根本没有出现。我知道问题出在animation()方法中。我只是不知道为什么它不起作用。

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

第一块代码是我正在尝试创建的动画方法。剩下的就是整个BattleGame课程。 “动画方法就在actionPerformed之后

感谢您的帮助,我知道很多代码,但我真的很绝望,我不确定为什么它不起作用''(

    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

2 个答案:

答案 0 :(得分:1)

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

到部署时,这些资源可能会成为embedded-resource。在这种情况下,必须通过URL而不是File访问资源。有关标记的信息,请参阅info page,了解构建网址的方法。

一般提示:更改表格的代码:

catch (Exception e) { 
    .. 

为:

catch (Exception e) { 
    e.printStackTrace(); // very informative! 
    ..

答案 1 :(得分:1)

  

我只是在代码中尝试了这种格式,我仍然得到错误,任何想法为什么它不会找到图像? - URL frames[0] = this.getClass().getResource("C:/Users/Connor/jGrasp/1.png");

保持简短,使用

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

你已经说过你的图像与课程在同一个包中..让它们保持在那里。

ProjectRoot
         src
            mypackage
                   MyClass.java
                   1.png

另请注意,在animation方法中,您创建了一个JPanel gui,其中添加了图片标签,但您永远不会将gui添加到任何内容中。