Reputation: 46
I have been trying to make this program display an image and then replace and then after a second it will remove the image and replace it with a different one after one second. Which image to display is controlled by a random int i. Everything works except the images stack up next to each other and aren't deleted. I have looked everywhere and still can't find anything that works for me.
public Frame() {
this.setTitle("Fast Number");
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel panel1 = new JPanel();
while(true){
System.out.println("Random Int: "+ i);
if(i == 1){
ImageIcon pic = new ImageIcon("//Users//evan//Documents//workspace//Fast Number//res//ArrowUp.png");
panel1.add(new JLabel(pic));
} else if (i == 2){
ImageIcon pic = new ImageIcon("//Users//evan//Documents//workspace//Fast Number//res//ArrowDown.png");
panel1.add(new JLabel(pic));
}else if (i == 3){
ImageIcon pic = new ImageIcon("//Users//evan//Documents//workspace//Fast Number//res//ArrowLeft.png");
panel1.add(new JLabel(pic));
}else if (i == 4){
ImageIcon pic = new ImageIcon("//Users//evan//Documents//workspace//Fast Number//res//ArrowRight.png");
panel1.add(new JLabel(pic));
}
try {
Thread.sleep(1000);
} catch (InterruptedException ex) {
Thread.currentThread().interrupt();
}
this.add(panel1);
this.pack();
this.setSize(256, 276); //Makes it so only one image is visible at once
this.setResizable(false);
this.setLocationRelativeTo(null);
i = RandomRange.Range(1, 4);
this.remove(panel1);
panel1.revalidate();
repaint();
}
Upvotes: 0
Views: 3049
Reputation: 324108
Don't create a new panel and don't create a new JLabel.
Instead add a JLabel to the frame when you create the frame and then just change the Icon of the label by using:
label.setIcon( pic );
Upvotes: 2
Reputation: 514
Take out add(panel1)
and remove(panel1)
, and use setContentPane(panel1)
instead.
Upvotes: 2