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