从 JFrame 中删除图像
Removing an Image off a JFrame
我一直试图让这个程序显示一个图像然后替换,然后在一秒钟后它会删除图像并在一秒钟后用不同的图像替换它。显示哪个图像由随机整数 i 控制。一切正常,除了图像彼此相邻堆叠并且不会被删除。我到处都看过,但仍然找不到适合我的东西。
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();
}
去掉add(panel1)
和remove(panel1)
,用setContentPane(panel1)
代替。
不要创建新面板,也不要创建新 JLabel。
而是在创建框架时将 JLabel 添加到框架,然后使用以下方法更改标签的图标:
label.setIcon( pic );
我一直试图让这个程序显示一个图像然后替换,然后在一秒钟后它会删除图像并在一秒钟后用不同的图像替换它。显示哪个图像由随机整数 i 控制。一切正常,除了图像彼此相邻堆叠并且不会被删除。我到处都看过,但仍然找不到适合我的东西。
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();
}
去掉add(panel1)
和remove(panel1)
,用setContentPane(panel1)
代替。
不要创建新面板,也不要创建新 JLabel。
而是在创建框架时将 JLabel 添加到框架,然后使用以下方法更改标签的图标:
label.setIcon( pic );