【问题标题】:Java swing: trouble understanding adding image to JLabelJava swing:难以理解将图像添加到 JLabel
【发布时间】:2019-04-20 07:20:48
【问题描述】:

希望大家在这美好的一天一切都好。

我正在学习挥杆,我对如何引用图像感到困惑。我知道我应该使用 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 的新文件夹并将文件移到那里,但似乎没有任何效果。这是它的样子

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

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();
        }

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

【问题讨论】:

    标签: java eclipse swing embedded-resource


    【解决方案1】:

    在你的情况下,你想让类加载器找到资源,像这样:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-03-21
      • 2020-10-03
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多