图像没有重新绘制,只是倍增 [英] Image not repainting, just multiplying

查看:173
本文介绍了图像没有重新绘制,只是倍增的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个JPanel实现了一个关键的监听器。它拉动并显示从另一个类中提取的图像。 NA将Key监听器传递给该类以获取许多图像中的一个并将其向一个方向移动2px。我的问题是,当我调用repaint()时,旧图像不会消失,所以我得到了一行图像。
事情是,当我将类与图像和JPanel类合并到一个bi final时,它完美地工作。

我已经对此进行了一些研究,我发现了双缓冲。如果我必须这样做那么为什么当它合并成一个大班级和单独的班级时它会起作用?
这是我的JPanel类的代码。谁能帮我?如果双缓冲是答案,有人可以向我解释。我得到理论而不是代码。

I have a JPanel implements a key listener. It pulls and displays an Image pulled from another class. NA the Key listener is passed to that class to get one of many images and move it 2px in a direction. My problem is that the old image does not disappear when I call repaint(), so i get a line of images. The thing is that when i combined the class with the image and the JPanel class in to one bi final it worked perfectly.
I have done some research on this and i found double buffering. If i have to do this then why would it work when combined into one big class vs separate classes? Here is my code for the JPanel class. Can any one help me? If double buffering is the answer can someone explain it to me. I get the theory but not the code.

import java.awt.Graphics;
import javax.swing.JPanel;
import java.awt.Image;
import java.awt.Graphics2D;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
  public class picPanel extends JPanel
  {
     walker w; 
     JPanel panel;

   public picPanel()
   {
     w=new walker();
     addKeyListener(new TAdapter());
     setFocusable(true);
     System.out.println(w.getX());
     System.out.println(w.getY());
     if(w.getImg()==null)
        System.out.println("is emty"); 

     repaint();
     //test();

    }

   public void paintComponent(Graphics g)
   {
    System.out.println("Hello");
    //Graphics2D g2d = (Graphics2D)g;

    Image m = w.getImg();
    g.drawImage(m,w.getX(),w.getY(),this);

   }

  private class TAdapter extends KeyAdapter 
  {  
   public void keyPressed(KeyEvent e) 
   {
     w.keyPressed(e);
     System.out.println("Hello");
     repaint();

   }
  }
 }


推荐答案

只需在 paintComponent 方法中调用 super.paintComponent

关于你的代码的一些进一步评论

Some further remarks about your code


  1. Swing旨在与 KeyBindings iso KeyListeners

  2. 为了让其他人轻松要阅读您的代码,请尊重 Java命名/代码约定,例如类以小写字母开头,变量用小写字母开头

  3. 在覆盖a时,添加 @Override 标签是一个好习惯方法。编译器不仅会检查签名是否匹配,而且还有其他人必须阅读您的代码以便快速查看您添加的方法,以及您只是覆盖哪些方法。

  1. Swing is designed to work with KeyBindings iso KeyListeners
  2. To make it easy for others to read your code, please respect the Java naming/code conventions, e.g. classes start with an uppercase letter and variables with a lowercase letter
  3. It is a good habit to adding @Override tags when you override a method. Not only will the compiler check that the signature matches, it also easier for somebody else who has to read your code to quickly see which methods you added, and which you simply override.

这篇关于图像没有重新绘制,只是倍增的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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