我正在使用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);


图像框代码如下

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;


所以为什么没有错误显示但我无法在图像框中得到任何图像

最佳答案

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


变成

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

09-25 20:45