Image not repainting, just multiplying

2019-07-16 12:48发布

问题:

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();

   }
  }
 }

回答1:

Just call super.paintComponent in your paintComponent method.

Some further remarks about your code

  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.