如何将文件位置作为参数作为字符串传递?
How to pass a file location as a parameter as a string?
目前我将一个硬编码的字符串文件位置传递给我的对象方法,该方法使用 .getResources()
方法中的字符串来加载图像文件。我现在尝试使用加载按钮选择一个图像,并将加载的文件位置作为字符串传递给 getResource()
方法。我正在使用 filename.getAbsolutePath()
方法检索文件位置,然后将 filename
变量传递到对象方法中,但这为我提供了以下错误 -
线程异常 "AWT-EventQueue-0" java.lang.NullPointerException.
它指向有错误的代码行是加载图像的 .getResources
行。我将 post 下面的代码以更好地理解我的问题。
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
}
您似乎使用 loadImage.getAbsolutePath()
创建了一个绝对文件名,但随后您尝试将其用作 class path resource 和 new ImageIcon(getClass().getResource(S))
。
相反,您应该将绝对文件名作为字符串传递给 ImageIcon
:
Icon flag = new ImageIcon(S);
此外,不要忘记将标签添加到框架中...
getContentPane().add(label);
此外,我现在不在 Windows,但我认为 filename.replaceAll("\\", "\\\\");
没有必要。
目前我将一个硬编码的字符串文件位置传递给我的对象方法,该方法使用 .getResources()
方法中的字符串来加载图像文件。我现在尝试使用加载按钮选择一个图像,并将加载的文件位置作为字符串传递给 getResource()
方法。我正在使用 filename.getAbsolutePath()
方法检索文件位置,然后将 filename
变量传递到对象方法中,但这为我提供了以下错误 -
线程异常 "AWT-EventQueue-0" java.lang.NullPointerException.
它指向有错误的代码行是加载图像的 .getResources
行。我将 post 下面的代码以更好地理解我的问题。
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
}
您似乎使用 loadImage.getAbsolutePath()
创建了一个绝对文件名,但随后您尝试将其用作 class path resource 和 new ImageIcon(getClass().getResource(S))
。
相反,您应该将绝对文件名作为字符串传递给 ImageIcon
:
Icon flag = new ImageIcon(S);
此外,不要忘记将标签添加到框架中...
getContentPane().add(label);
此外,我现在不在 Windows,但我认为 filename.replaceAll("\\", "\\\\");
没有必要。