gpt4 book ai didi

Java Swing : trouble understanding adding image to JLabel

转载 作者:行者123 更新时间:2023-11-29 07:25:43 25 4
gpt4 key购买 nike

我希望在这个美好的日子里每个人都过得很好。

我正在学习 swing,我对如何引用图像感到困惑。我知道我应该使用 JLabel,然后使用 this.add(); 将该 JLabel 添加到框架中,但即使在这里查看 oracle 文档:

https://docs.oracle.com/javase/6/docs/api/javax/swing/ImageIcon.html

目前还不清楚如何在不给出完整路径的情况下引用文件

C:\Users\someUser\eclipse-workspace\andSoOn.png

我不能那样做。我必须在完成后将我的工作发送给我的老师,并且代码不会像在我的系统上那样引用该文件。我尝试了几件事,最后在 eclipse 的 src 中创建了一个名为 ImageAssets 的新文件夹并将文件移到那里,但似乎没有任何效果。这是它的样子

I added a folder called ImageAssets

这是我尝试显示包内图像的示例。

import java.awt.*;
import javax.swing.*;

public class Hangman extends JFrame
{
JButton playGameButton,
OptionsButton;
private ImageIcon hangman7;
private JLabel mainLabel;

public static void main(String[] args)
{
new Hangman();
}

public Hangman()
{
this.setSize(1000,800);
this.setLocationRelativeTo(null);
this.setVisible(true);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setTitle("Hangman");
this.setResizable(false);
playGameButton = new JButton("Start Game");
OptionsButton = new JButton("Options");

//hangman7 = new ImageIcon(getClass().getResource("Images\\ hangman7.png"));//just an attempt at something
mainLabel = new JLabel();
mainLabel.setIcon(new ImageIcon("hangman7.png"));


JPanel somePanel = new JPanel();
somePanel.setLayout(new BorderLayout());
somePanel.add(playGameButton, BorderLayout.WEST);
somePanel.add(OptionsButton, BorderLayout.EAST);
somePanel.add(mainLabel, BorderLayout.CENTER);

this.add(somePanel);
this.validate();
}

非常感谢您花时间帮助我。我试图非常详细;如果有任何不清楚的地方,请询问。

最佳答案

在您的情况下,您想让类加载器找到资源,如下所示:

mainLabel.setIcon(
new ImageIcon(getClass().getResource("/ImageAssets/hangman7.png")));

关于Java Swing : trouble understanding adding image to JLabel,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53349106/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com