将 ImageIcon 添加到 JPanel 不起作用
Adding ImageIcon to JPanel not working
我正在尝试将 ImageIcon 添加到我的 JPanel。
ImageIcon image = new ImageIcon("image.png", null);
JLabel label = new JLabel(image, JLabel.CENTER);
panel.add(label);
好的。该图像位于与 class...
相同的文件夹中
com.package
|- mainclass.java
|- image.png
V
无论出于何种原因,图像图标都不会显示在 JPanel 中。
我尝试/抓住了它,但没有用。完全没有错误!
我在 Windows.
您必须指定 full path
,从您的应用程序的 root
可以看出。
在您的情况下,您必须使用 new ImageIcon("com/package/image.png", null)
。
ImageIcon(String)
假定指定的String值是文件系统上的一个文件
根据您的描述,我猜该图像嵌入在应用程序中,这意味着它不再作为文件访问,而是需要作为 URL
或 InputStream
访问
因为图像和 class 在同一个包中,你可以使用类似
ImageIcon img = new ImageIcon(getClass().getResource("image.png"));
假设您从 MainClass
加载它
编辑
我查看了一些具有类似情况的旧代码,结果我先将图像添加到 JLabel,然后再添加到 JPanel。
尝试将图像添加到 JLabel,然后将该 JLabel 添加到 JPanel,如下所示。
ImageIcon image = new ImageIcon(this.getClass().getResource("image.png"));
JLabel picLabel = new JLabel(image);
panel.add(picLabel);
我正在尝试将 ImageIcon 添加到我的 JPanel。
ImageIcon image = new ImageIcon("image.png", null);
JLabel label = new JLabel(image, JLabel.CENTER);
panel.add(label);
好的。该图像位于与 class...
相同的文件夹中com.package
|- mainclass.java
|- image.png
V
无论出于何种原因,图像图标都不会显示在 JPanel 中。 我尝试/抓住了它,但没有用。完全没有错误!
我在 Windows.
您必须指定 full path
,从您的应用程序的 root
可以看出。
在您的情况下,您必须使用 new ImageIcon("com/package/image.png", null)
。
ImageIcon(String)
假定指定的String值是文件系统上的一个文件
根据您的描述,我猜该图像嵌入在应用程序中,这意味着它不再作为文件访问,而是需要作为 URL
或 InputStream
访问
因为图像和 class 在同一个包中,你可以使用类似
ImageIcon img = new ImageIcon(getClass().getResource("image.png"));
假设您从 MainClass
编辑
我查看了一些具有类似情况的旧代码,结果我先将图像添加到 JLabel,然后再添加到 JPanel。
尝试将图像添加到 JLabel,然后将该 JLabel 添加到 JPanel,如下所示。
ImageIcon image = new ImageIcon(this.getClass().getResource("image.png"));
JLabel picLabel = new JLabel(image);
panel.add(picLabel);