简体   繁体   English

Java图标文件未显示图像

[英]Java Icon File not showing image

I am using a Imagebox JFrame to add image, I want to change image in runtime so I add following code but nothing is displayed. 我正在使用Imagebox JFrame添加图像,我想在运行时更改图像,因此我添加了以下代码,但未显示任何内容。

 javax.swing.JFileChooser filechooser = new javax.swing.JFileChooser();
        filechooser.showDialog(this,"ok");
        File f =  filechooser.getSelectedFile();
        txt_Image.setText(f.getName());        
        FileName = f.getPath()+f.getName();
        Image im= Toolkit.getDefaultToolkit().createImage(FileName);
        ImageIcon receivedIcon =null;
        receivedIcon.setImage(im);
        imagebox1.setimageFile(receivedIcon);

the image box code is below 图像框代码如下

public class imagebox extends JPanel {
    public void setimageFile(Icon icon) {
       imageFile=icon;
    }
    @Override
    public void paint(Graphics g) {
        super.paint(g);
        if (imageFile != null) {            
            Image imageF=  ((ImageIcon)imageFile).getImage();
           g.drawImage(imageF, 0, 0, getWidth(), getHeight(), this);
        } else {
            g.drawLine(0, 0, getWidth(), getHeight());
            g.drawLine(0, getHeight(), getWidth(), 0);
        }
    }
    private Icon imageFile = null;

so why no error showing but I cant get any image in my imagebox 所以为什么没有错误显示但我无法在图像框中获得任何图像

if you only to display the Images then better would be to use Icon/ImageIcon directly, (to avoiding Casting or whatever) put this Icon to the JLabel instead of to the JPanel 如果仅显示Images那么更好的方法是直接使用Icon / ImageIcon (以避免进行Casting或其他操作)将此图标放置到JLabel而不是JPanel

if you want change your Icon on Runtime, then you code would be 如果您想在运行时更改Icon ,那么您的代码将是

myLabel.setIcon(myIcon);
revalidate();
repaint(); 

this code must be done on the EDT, otherwise you have to wrap am code lines into invokeLater() 此代码必须在EDT上完成,否则您必须将代码行包装到invokeLater()中

ImageIcon receivedIcon = null;
receivedIcon.setImage(im);

changed to 变成

ImageIcon receivedIcon = new ImageIcon();
receivedIcon.setImage(im);

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

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