从JFrame中删除图像

时间:2015-01-28 21:29:39

标签: java swing jframe jlabel imageicon

我一直试图让这个程序显示一个图像,然后更换,然后在一秒钟后它将删除图像并在一秒钟后用另一个图像替换它。要显示的图像由随机int 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();
    }

2 个答案:

答案 0 :(得分:2)

取出add(panel1)remove(panel1),然后改用setContentPane(panel1)

答案 1 :(得分:2)

不要创建新面板,也不要创建新的JLabel。

而是在创建框架时向框架添加JLabel,然后使用以下命令更改标签的图标:

label.setIcon( pic );