目前,我将硬编码的字符串文件位置传递给我的对象方法,该方法使用方法中的字符串.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
}