我不确定我是否使用此代码指向正确的位置,我试图访问的图像标题为Flower0.png
等。
它们位于与本项目的其余代码相同的目录中。该类位于名为hangman.ui
的src文件夹中,.png
文件位于名为Resources
的目录文件夹中。
也许getClass().getResource
是不对的?
这是我第一次尝试将图像放入GUI。
非常感谢你的帮助!
public WiltingFlowerRendererRemix(HangmanLogic logic)
{
panel = new JPanel();
panel.setLayout(new BorderLayout());
imageLabel = new JLabel();
panel.add(imageLabel, BorderLayout.CENTER);
int numberOfImages = 10;
images = new ImageIcon[numberOfImages];
for (int i = 0; i < numberOfImages; i++)
{
images[i] = new ImageIcon(getClass().getResource("Flower"+Integer.toString(i) + ".png"));
}
}
你说图像在一个名为"Resources"的文件夹中?你可以像这样加载图片:
BufferedImage image = ImageIO.read(getClass().getResource("/Resources/Flower0.png"));
ImageIcon icon = new ImageIcon(image);
要在GUI上使用它,您可以使用JLabel。
JLabel label = new JLabel();
label.setIcon(icon);
然后将标签添加到面板中,例如
For me Works…
根据Maven:https://maven.apache.org/guides/introduction/introduction-to-the-standard-directory-layout.html
src/main/resources
: Application/Library resources
然后我把图标放在这个位置:
PROJECTNAMEsrcmainresourcesusedPictures
--Open.png
清理和构建。你可以在这里检查文件的位置得到....
PROJECTNAMEtargetclassesusedPictures
--Open.png
现在是使用图标的例子:
button.setIcon(
new javax.swing.ImageIcon(
getClass().getClassLoader().getResource("usedPictures/Open.png")
)
);