java 使用 JFileChooser 将图像加载到 JFrame

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/10737029/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-31 02:19:04  来源:igfitidea点击:

image loading using a JFileChooser into a JFrame

javaswingjpaneljlabelimageicon

提问by

I am trying to write a code that displays an image selected using a JFileChooser into another JFrame .I tried the following code below but only got the following errors.

我正在尝试编写一个代码,将使用 JFileChooser 选择的图像显示到另一个 JFrame 中。我尝试了下面的代码,但只得到以下错误。

Exception in thread "main" java.lang.NullPointerException
at javax.swing.ImageIcon.<init>(ImageIcon.java:228)
at power.<init>(fCGUI.java:53)
at fCGUI.main(fCGUI.java:11)

Here is the code:

这是代码:

import javax.imageio.ImageIO;
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;

public class fCGUI
{
    public static void main(String []args)
    {
        power p=new power();
        p.setVisible(true);
    }
}

class power extends JFrame
{
    JFileChooser chooser;
    BufferedImage img;
    JButton button,button2;
    JFrame comp;
    String filename;
    File file ; 

    public power()
    {
        setSize(450,450);
        panel.setLayout(new BorderLayout());

        JPanel panel=new JPanel();
        getContentPane().add(panel);
        button =new JButton("press");

        panel.add(button,BorderLayout.NORTH);

        chooser = new JFileChooser();

        ActionListener action=new ActionListener()
        {
            public void actionPerformed(ActionEvent e)
            {
                if (e.getSource()==button)
                {
                    chooser.showOpenDialog(null);
                    file = chooser.getSelectedFile();

                    try
                    {
                        img=ImageIO.read(file);
                    }
                    catch(IOException e1) {}
                }

                if (e.getSource()==button2)
                {
                    comp.setVisible(true);
                }
            }
        };

        ImageIcon icon=new ImageIcon(img);
        JLabel label=new JLabel(icon);

        JPanel secpanel=new JPanel();

        comp=new JFrame();
        comp.setSize(650,500);
        comp.setLayout(new BorderLayout());
        comp.setTitle("View Report");

        JRootPane compPane=comp.getRootPane();
        Container contePane=compPane.getContentPane();
        contePane.add(secpanel);

        secpanel.add(label,BorderLayout.CENTER);

        button2=new JButton("access");
        button2.addActionListener(action);
        button.addActionListener(action);

        panel.add(button2,BorderLayout.SOUTH);
    }
}

采纳答案by wattostudios

The value of imgwill only have a real value after the user click the button and chooses the file to display. Until this time, the value of imgis null, so when it continues through your method and calls the line ImageIcon icon=new ImageIcon(img);, it is trying to create an ImageIconobject for null.

的值img只有在用户单击按钮并选择要显示的文件后才会有实际值。直到这个时候,价值img就是null,所以当它继续通过你的方法,并调用线ImageIcon icon=new ImageIcon(img);,它试图创建ImageIcon的对象null

To correct this, you should only be creating the ImageIconwhen the user has chosen the file. Here is a change that should be closer to working correctly. (see the comments //ADDEDand //REMOVEDin the code below to see the changes...

要更正此问题,您应该仅ImageIcon在用户选择文件时创建。这是一个应该更接近正常工作的更改。(请参阅下面的注释//ADDED//REMOVED代码以查看更改...

...
class power extends JFrame {
    JFileChooser chooser;
    BufferedImage img;
    JButton button,button2;
    JFrame comp;
    String filename;
    File file ; 
    JLabel label; // ADDED

    public power() {
    ...
            public void actionPerformed(ActionEvent e) {
                if (e.getSource()==button) {
                    chooser.showOpenDialog(null);
                    file = chooser.getSelectedFile();

                    try {
                        img=ImageIO.read(file);
                        ImageIcon icon=new ImageIcon(img); // ADDED
                        label.setIcon(icon); // ADDED

                        Dimension imageSize = new Dimension(icon.getIconWidth(),icon.getIconHeight()); // ADDED
                        label.setPreferredSize(imageSize); // ADDED

                        label.revalidate(); // ADDED
                        label.repaint(); // ADDED
                    }
                    catch(IOException e1) {}
                }

                if (e.getSource()==button2){
                    comp.setVisible(true);
                }
            }
        };

        //ImageIcon icon=new ImageIcon(img); // REMOVED
        //JLabel label=new JLabel(icon); // REMOVED
        label = new JLabel(); // ADDED

        JPanel secpanel=new JPanel();
        ...

To explain what I've changed...

为了解释我改变了什么......

  1. The labelwill now be created as an empty JLabelwhen you first start the program. It is also stored as a global variable so we can access it later
  2. When the button is clicked, the imgis created, as before, and then it is loaded into your labelusing setIcon();
  3. The label is resized, then revalidate()and repaint()to make sure that the image is drawn after it is set.
  1. label会现为空创建JLabel当您第一次启动该程序。它也被存储为一个全局变量,以便我们以后可以访问它
  2. 单击按钮时img,会像以前一样创建该按钮,然后将其加载到您的label使用中setIcon();
  3. 该标签大小,然后revalidate()repaint()以确保作出这样的设置完成后绘制图像。

回答by Radu Murzea

The ImageIO.readis only executed when that specific JButtonis pressed. That is because it's inside the ActionListener. Because of this, imgis null which causes a NullPointerExceptionwhen ImageIcon icon=new ImageIcon(img)is executed.

ImageIO.read当特定的仅执行JButton被按下。那是因为它在ActionListener. 因此,imgis null 导致执行NullPointerExceptionwhen ImageIcon icon=new ImageIcon(img)