JFrame中的动画序列 [英] Animation sequence in JFrame

查看:80
本文介绍了JFrame中的动画序列的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想创建一个 JFrame 并在其中放置一系列动画图像。但是图像不会出现在框架窗口中。我只希望基本的故障排除提示使它显示在窗口中。



我的问题:
为什么窗口不显示任何图片?它显示的窗口背景颜色为蓝色,仅此而已。请告诉我一种将图像存储在变量中并循环显示的有效方法。

  import java.awt。*; 
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.image.BufferedImage;

import javax.imageio.ImageIO;
import javax.swing。*;

import java.io. *;



公共类游戏扩展JLabel实现了ActionListener {


/ **
*
* /
private static final long serialVersionUID = 1L;
公共静态游戏等等;
BufferedImage nekopics [] = new BufferedImage [7];

BufferedImage currentimg;
public String nekosrcs [];
int xpos;

计时器计时器;

public Game()引发IOException
{
JFrame jframe = new JFrame();




nekosrcs = new String [] { walk1.png, walk2.png,

walk3。 png, walk4.png, walk5.png,

walk6.png};

jframe.setTitle( Game);
jframe.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
jframe.setLayout(new FlowLayout());

jframe.setSize(400,400);
jframe.setResizable(false);
jframe.setVisible(true);

jframe.getContentPane()。setBackground(Color.BLUE);




$ b for(int i = 0; i
nekopics [i] = ImageIO.read(new FileInputStream( D:/ Programs
/ pics + nekosrcs [i]));

}

for(int i = 0; i< nekopics.length; i ++){
timer = new Timer(1000,this);
timer.setInitialDelay(0);
timer.start();
currentimg = nekopics [i];

repaint();


}



}

public void paintComponent(Graphics g)
{
super.paint(g);

g.drawImage(currentimg,100,100,this);
}



public static void main(String [] args)引发IOException {

blah = new Game();



}

public void actionPerformed(ActionEvent e){
// TODO自动生成的方法存根

}




}


解决方案

好的,您的代码中存在很多问题,让我们逐一介绍它们:


  1. 行之间有很多空格,这会使您的代码更大且更难阅读


  2. 您没有正确缩进您的代码(请参见代码中的最后一个} ,该级别与其他代码处于同一级别;您的 循环等),这也会使代码更难以阅读和理解


  3. 您正在创建 JFrame 但扩展了 JLabel ,我不确定为什么要这么做,所以可以使用 paintComponent()方法,这不是必需的,在我的代码上,您可以看到不扩展任何 Component


  4. 如果您尚未阅读Swing Timer 文档,您应该单击该链接并阅读 ActionListener 参数可以。在这种情况下,我们将使用此侦听器调用 repaint()方法并更新 currentImage (或下面的代码中的 nextImage )并相应地更改图像。您没有这样做。


  5. 您还创建了1个以上的 Timer ,您在此处创建了6个!所有这些都是新手,但是在时间结束后他们没有采取行动

     为(int i = 0; i  timer = new Timer(1000,this); 
    timer.setInitialDelay(0);
    timer.start();
    currentimg = nekopics [i];
    repaint();
    }


  6. 您不必要地更改了<$ c $的可见性c> paintComponent()方法从受保护的

  7. 变为公共 >






不过,我想祝贺您没有使用 null 布局并遵循我在上面的注释中提出的建议。






最后是更改一个代码的代码 Timer 中的另一个图像如下,您可以将其复制粘贴并更改图像名称,以便查看其工作原理。

  import java.awt.Dimension; 
import java.awt.Graphics;
import java.awt.Image;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.FileInputStream;
import java.io.IOException;

import javax.imageio.ImageIO;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
import javax.swing.Timer;

公共类ImageSequence {
私有JFrame框架;
个JPanel专用窗格;
私人计时器;
private int nextImage = 0;
private String [] images = { tokyo, tokyo2, starwars};
private Image img = null;
public static void main(String args []){
SwingUtilities.invokeLater(new Runnable(){
@Override
public void run(){
new ImageSequence ().createAndShowGui();
}
});
}

public void createAndShowGui(){
frame = new JFrame( Image Sequence);
timer = new Timer(1000,listener);
窗格= new JPanel(){
@Override
受保护的void paintComponent(图形g){
super.paintComponent(g);
try {
img = ImageIO.read(new FileInputStream( / home / jesus / Pictures / + images [nextImage] + .jpg));
} catch(IOException e){
// TODO自动生成的catch块
e.printStackTrace();
}
g.drawImage(img,0,0,200,200,this);
}

@Override
public Dimension getPreferredSize(){
return new Dimension(200,200);
}
};

timer.start();

frame.getContentPane()。add(pane);
frame.pack();
frame.setVisible(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}

ActionListener侦听器= new ActionListener(){
@Override
public void actionPerformed(ActionEvent event){
System.out.println(nextImage );
nextImage = nextImage< images.length-1? nextImage + 1:0;
System.out.println(nextImage);
pane.repaint();
}
};
}


I wanted to create a JFrame and put a sequence of images for animation in there. But the images don't appear in the frame window. I just want basic troubleshooting tips to make it appear in the window. Just edit the code for an answer if you can.

My question: Why isn't the window displaying any pictures? It shows a window with a background color of blue, but that's it. Please tell me an efficient way to store images in variables and display it in a loop.

import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.image.BufferedImage;

import javax.imageio.ImageIO;
import javax.swing.*;

import java.io.*;



public class Game extends JLabel implements ActionListener{


 /**
  * 
  */
 private static final long serialVersionUID = 1L;
 public static Game blah;
  BufferedImage nekopics[] = new BufferedImage[7];

 BufferedImage currentimg;
 public String nekosrcs[];
 int xpos;

 Timer timer;

 public Game() throws IOException
 {
      JFrame jframe = new JFrame();




      nekosrcs = new String[] { "walk1.png", "walk2.png",

              "walk3.png", "walk4.png", "walk5.png",

              "walk6.png"};

    jframe.setTitle("Game");
    jframe.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    jframe.setLayout(new FlowLayout());

    jframe.setSize(400, 400);
    jframe.setResizable(false);
    jframe.setVisible(true);

    jframe.getContentPane().setBackground(Color.BLUE);




     for (int i=0; i < nekopics.length; i++) {

 nekopics[i] = ImageIO.read(new FileInputStream("D:/Programs 
                                              /pics"+nekosrcs[i]));

     }

     for (int i=0; i < nekopics.length; i++) {
         timer = new Timer(1000, this);
            timer.setInitialDelay(0);
            timer.start();
         currentimg = nekopics[i];

         repaint();


     }



 }

public void paintComponent(Graphics g)
{
    super.paint(g);

    g.drawImage(currentimg,100,100,this);
}



 public static void main(String[] args) throws IOException {

blah = new Game();



}

public void actionPerformed(ActionEvent e) {
// TODO Auto-generated method stub

}




}

解决方案

Alright, there are a lot of problems in your code, let's step into each of them:

  1. You have a lot of spaces between lines, that makes your code a lot larger and harder to read

  2. You haven't indented your code correctly (see the last } on your code, it's at the same level than the others; your for loops, etc), it makes the code so much harder to read and understand as well

  3. You're creating a JFrame but extending JLabel, I'm not sure why you're doing this, if you're doing it so you can use the paintComponent() method, it's not necessary, on my code you can see how you can do it w/o extending any Component

  4. If you haven't read the Swing Timer docs you should click that link and read what the ActionListener parameter does. In this case, we're going to use this listener to call the repaint() method and update our currentImage (or nextImage in the code below) and change the image accordingly. You failed to do this.

  5. You were creating more than 1 Timer too, you created 6 here! All of them new but they had no action to do when the time finished

    for (int i=0; i < nekopics.length; i++) {
        timer = new Timer(1000, this);
        timer.setInitialDelay(0);
        timer.start();
        currentimg = nekopics[i];
        repaint();
    }
    

  6. You're changing unnecessarily the visibility of the paintComponent() method to public from protected


However I want to congratulate you for not using a null layout and following the recommendations I made on the comments above.


And finally the code that changes one image for another inside a Timer is the following, you can copy-paste it and change the image's names so you can see how it works.

import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Image;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.FileInputStream;
import java.io.IOException;

import javax.imageio.ImageIO;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
import javax.swing.Timer;

public class ImageSequence {
    private JFrame frame;
    private JPanel pane;
    private Timer timer;
    private int nextImage = 0;
    private String[] images = {"tokyo", "tokyo2", "starwars"};
    private Image img = null;
    public static void main (String args[]) {
        SwingUtilities.invokeLater(new Runnable() {
            @Override
            public void run() {
                new ImageSequence().createAndShowGui();
            }
        });
    }

    public void createAndShowGui() {
        frame = new JFrame("Image Sequence");
        timer = new Timer(1000, listener);
        pane = new JPanel() {
            @Override
            protected void paintComponent(Graphics g) {
                super.paintComponent(g);
                try {
                    img = ImageIO.read(new FileInputStream("/home/jesus/Pictures/" + images[nextImage] + ".jpg"));
                } catch (IOException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
                g.drawImage(img , 0, 0, 200, 200, this);
            }

            @Override
            public Dimension getPreferredSize() {
                return new Dimension(200, 200);
            }
        };

        timer.start();

        frame.getContentPane().add(pane);
        frame.pack();
        frame.setVisible(true);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    }

    ActionListener listener = new ActionListener() {   
        @Override
        public void actionPerformed(ActionEvent event) {
            System.out.println(nextImage);
            nextImage = nextImage < images.length - 1 ? nextImage + 1 : 0;
            System.out.println(nextImage);
            pane.repaint();
        }
    };
}

这篇关于JFrame中的动画序列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆