gee*_*que 1 java eclipse swing embedded-resource
我希望每个人在这美好的一天都做得很好.
我正在学习摇摆,我对如何引用图像感到困惑.我知道我应该使用JLabel,然后使用this.add();将该JLabel添加到Frame中,但是在这里查看oracle文档:
https://docs.oracle.com/javase/6/docs/api/javax/swing/ImageIcon.html
目前还不清楚如何在不给出整个路径的情况下引用文件
C:\ Users \用户SomeUser是否\ Eclipse的工作空间\ andSoOn.png
而我不能那样做.一旦完成,我必须将我的工作发送给我的老师,并且代码不会像在我的系统上那样引用文件.我尝试了几件事,最后我在eclipse的src中创建了一个名为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();
}
Run Code Online (Sandbox Code Playgroud)
非常感谢你花时间帮助我.我试着非常详细; 如果有什么不清楚请问.
在您的情况下,您希望让类加载器找到资源,如下所示:
mainLabel.setIcon(
new ImageIcon(getClass().getResource("/ImageAssets/hangman7.png")));
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
22 次 |
| 最近记录: |