简体   繁体   English

java jLabel图像不更新

[英]java jLabel image does not update

I'm creating a feedback label that displays the picture that the user has chosen in a file dialog. 我正在创建一个反馈标签,以显示用户在文件对话框中选择的图片。

The moment when a picture file is selected, the label will update itself into that image of which the user has clicked. 选择图片文件的那一刻,标签会自动更新为用户单击的图片。

The first time when the picture is chosen it works fine, however when another picture is chosen for the 2nd time onwards, it remains as the first picture. 第一次选择图片时,它可以正常工作,但是当第二次以后选择另一张图片时,它将保留为第一张图片。

Codes: 代码:

 private void jButton3ActionPerformed(java.awt.event.ActionEvent evt) {                                         
        //browse button
        FileDialog fd = new FileDialog(this, "Choose a file", FileDialog.LOAD);
        fd.setDirectory("C:\\");
        fd.setFile("*.jpg"); // jpg files only
        fd.setVisible(true);
        String filename = fd.getFile();
        if (filename == null) {
            System.out.println("You cancelled the choice");
        } else {
            savePicture("temp"); // save it in temp.jpg. This overwrites any existing picture. 
            ImageIcon imgThisImg = null; 
            imgThisImg = new ImageIcon(absfilePath+ "/temp.jpg"); 
            jLabel7.setIcon(null);
            jLabel7.setIcon(imgThisImg);
            jLabel7.revalidate();
            jLabel7.repaint();
        }

During debugging, the moment after savePicture() function is executed, the directory picture is updated. 在调试过程中,执行savePicture()函数后,将更新目录图片。 Therefore it's not an issue with overwritting the file. 因此,覆盖文件不是问题。 The file is overwritten correctly, why does it still display the previous image? 该文件已正确覆盖,为什么仍显示前一张图像? Is there a cache or something that i need to clear? 是否有缓存或需要清除的内容?

Thanks. 谢谢。

Using ImageIO to the read file works best. 使用ImageIO读取文件效果最佳。 Can be achieved using the following line. 可以使用以下行来实现。 jLabel7.setIcon(new JLabel(new ImageIcon(ImageIO.read(new File("C:\\\\Users\\\\Cameron Gillespie\\\\Documents\\\\NetBeansProjects\\\\OnlineCabsClient\\\\src\\\\images\\\\taxiBackground.png")))));

You are taking the label then setting the icon. 您正在贴标签,然后设置图标。 Creating a new label and ImageIcon. 创建一个新标签和ImageIcon。 Then using ImageIO to read the file. 然后使用ImageIO读取文件。 Reading the image and printing it to the label. 读取图像并将其打印到标签上。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM