我制作了这个程序,它应该在我的桌面上打开一个图像,但当我运行它时,它给了我错误java.lang.ArrayIndexOutOfBoundsException
。我做错了什么?
import java.awt.BorderLayout;
import java.awt.image.BufferedImage;
import java.io.File;
import javax.imageio.ImageIO;
import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.SwingUtilities;
import javax.swing.WindowConstants;
public class Image {
public static void main(String[] args) throws Exception
{
new Image(args[0]);
}
public Image(final String filename) throws Exception
{
SwingUtilities.invokeLater(new Runnable()
{
public void run()
{
JFrame editorFrame = new JFrame("C:/Users/Username/Desktop/index.jpg");
editorFrame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
BufferedImage image = null;
try
{
image = ImageIO.read(new File(filename));
}
catch (Exception e)
{
e.printStackTrace();
System.exit(1);
}
ImageIcon imageIcon = new ImageIcon(image);
JLabel jLabel = new JLabel();
jLabel.setIcon(imageIcon);
editorFrame.getContentPane().add(jLabel, BorderLayout.CENTER);
editorFrame.pack();
editorFrame.setLocationRelativeTo(null);
editorFrame.setVisible(true);
}
});
}
我会得到什么这个错误:
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 0
at Image.main(Image.java:15)
发布于 2015-07-06 22:59:35
您必须将命令行参数传递给main()
方法。我们通过Image()
构造函数传递的参数。
new Image(args[0]);
请看下面的命令行概念。
什么是命令行参数?
应用程序可以从命令行接受任意数量的参数。这些参数称为命令行参数。这允许用户在应用程序启动时指定配置信息。
如何传递命令行参数?
用户在调用应用程序时输入命令行参数,并在要运行的类的名称后指定它们。
例如,假设一个名为Sort的Java应用程序对文件中的行进行排序。要对名为friends.txt的文件中的数据进行排序,用户可以输入:
java Sort friends.txt
这里:Sort--类名
friends.txt -命令行参数。
当应用程序启动时,运行时系统通过字符串数组将命令行参数传递给应用程序的main方法。在前面的示例中,传递给排序应用程序的命令行参数在一个数组中,该数组包含单个字符串:"friends.txt“。
更新
您可以使用空格作为分隔符来传递多个命令行参数。
喜欢
java Sort stack.txt overflow.txt
如何在Eclipse中传递命令行参数?
转到包资源管理器或导航器视图上的程序
选择该程序->右键单击程序后选择Run As -> Run Configuration ->在顶部选择 arguments second option ->在程序参数上给出参数
请参见下面的屏幕截图:
发布于 2015-07-06 22:46:15
看起来您忘记了传递命令行参数。
new Image(args[0]);
https://stackoverflow.com/questions/31248848
复制相似问题