1

目前,我将硬编码的字符串文件位置传递给我的对象方法,该方法使用方法中的字符串.getResources()来加载图像文件。我现在正在尝试使用加载按钮选择图像并将加载的文件位置作为字符串传递给getResource()方法。我正在使用该filename.getAbsolutePath()方法来检索文件位置,然后将filename变量传递给对象方法,但是这为我提供了以下错误-线程中"AWT-EventQueue-0" java.lang.NullPointerException. 的异常它指向的代码行有错误.getResources是加载图像的行。我将发布下面的代码以更好地理解我的问题。

btnLoad.addActionListener(new ActionListener() {
              @Override
              public void actionPerformed(ActionEvent e) {


                 JFileChooser fc = new JFileChooser();
                 if (fc.showOpenDialog(null) == JFileChooser.APPROVE_OPTION)
                 {
                    File loadImage = fc.getSelectedFile();
                    String filename = loadImage.getAbsolutePath();
                    filename = filename.replaceAll("\\\\", "\\\\\\\\");
                    picLocation = filename;
                    ImageSwing imageSwing = new ImageSwing(filename);
                    System.out.println(filename);
                 }
              }

文件名的输出是正确的,但它仍然不会传递到对象中。

  public class ImageSwing extends JFrame
  {
  public JLabel label;

  public ImageSwing(String S){

  super("Card Stunt");                //Window Title
  setLayout(new FlowLayout());        //lookup grid layout


  Icon flag = new ImageIcon(getClass().getResource(S));          
  label = new JLabel(flag);
  label.setToolTipText(S);
  setSize(1350, 800);
  //setMinimumSize(new Dimension(1200, 760));

  }//main
 }
4

1 回答 1

1

似乎您使用 . 创建了一个绝对文件名loadImage.getAbsolutePath()但随后您尝试使用.new ImageIcon(getClass().getResource(S))

相反,您应该将绝对文件名作为字符串传递给ImageIcon

Icon flag = new ImageIcon(S);

另外,不要忘记将标签添加到框架...

getContentPane().add(label);

另外,我现在不在 Windows 上,但我认为没有filename.replaceAll("\\\\", "\\\\\\\\");必要。

于 2015-04-27T11:19:54.463 回答