Hay I'm trying to learn how to use Graphics in java and I'm writing a very simple code that takes an image and moves it across the window in a line and when it hits the edge of the window it moves down a few pixels and starts back at the other end.
My problem is that my program isn't removing the previous image when it repaints() so instead of 1 image just being moved across I'm getting a long string of images (I'm also having a weird problem where the button I use to repaint() is getting it's image duplicated at the top left of the window but 1 issue at a time I think)
here's the code for the 2 class files I'm using:
public class TestieImages extends JFrame implements ActionListener{
ImagePanel jj =new ImagePanel();
TestieImages(){
setTitle("TestFrame");
setResizable(false);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setSize(582,604);
JButton butt = new JButton("The butt");
butt.addActionListener(this);
butt.setActionCommand("1");
butt.setBounds(200, 200, 80, 24);
add(butt);
add(jj);
setVisible(true);
}
@Override
public void actionPerformed(ActionEvent e) {
String action= e.getActionCommand();
int x=jj.getXCoord();
int y=jj.getYCoord();
if (action.equals("1")){
if (x<=448){
jj.setX(x+64);
}
else{
jj.setX(0);
jj.setY(y+64);
}
jj.repaint();
}
}
public static void main(String[] args) {
JFrame j = new TestieImages();
} }
ImagePanel
public class ImagePanel extends JPanel{
private int x=0;
private int y=0;
private BufferedImage image;
ImagePanel() {
try {
image = ImageIO.read(new File("C:\\Users\\dleitrim09\\Documents\\NetBeansProjects\\TestieImages\\src\\Resources\\Wall.png"));
} catch (IOException ex) {
// handle exception...
}
}
void setX (int newx){
x=newx;
}
void setY (int newy){
y=newy;
}
int getXCoord (){
return x;
}
int getYCoord (){
return y;
}
@Override
protected void paintComponent(Graphics g) {
g.drawImage(image, x, y, null);
}
}
also here's the Output:
Think of your window as a painting. When you paint something to it, you paint over what is already there. So if you just paint your image then the image you painted previously still remains there.
So you need to 'wipe your canvas' before painting your image to the window. This will be done by the super class if you call super.paintComponent(g)
before your call to drawImage()
.