3

我不确定问题出在哪里。是在路上吗?尽管代码语法中完全没有错误,但图像未显示。我应该提供整个路径还是只将图像放在目录中并调用它的名称?谢谢你。

public class NetworkingGame {

private JFrame jfrm;

NetworkingGame(){
    jfrm = new JFrame("Angry Painters");
    jfrm.setSize(800, 480);
    jfrm.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    jfrm.setVisible(true);

}// end of constructor

public void ImageLoading(){
    ImageIcon i = new ImageIcon("C:/Users/TOSHIBA/Documents/NetBeansProjects/NetworkingGame/build/classes/angry-painters.jpeg");
    JLabel jl = new JLabel(i);
    jfrm.add(jl);
}

public static void main(String[] args) throws Exception{

    SwingUtilities.invokeLater(new Runnable(){

        @Override
        public void run(){

            NetworkingGame ng = new NetworkingGame();
            ng.ImageLoading();
        } // end of run method
    }); // end of Runnable

   }//end of main method
}//end of class NetworkingGame
4

4 回答 4

4

不要将文件路径用作图标位置,因为这仅适用于您的计算机。你真的不能指望世界上所有的机器都有 C:/Users/TOSHIBA ...angry-painters.jpeg 在正确的地方!

复制您使用的源代码 (.java) 类旁边的文件,然后调用

 new ImageIcon(getClass().getResource("angry-painters.jpeg"));

构建器应将图像资源复制到类文件夹本身。

于 2013-02-01T10:05:30.270 回答
2

尝试使用类似这样的路径:

jLabel1.setIcon(new ImageIcon("c:\\Users\\xyz\\Documents\\NetBeansProjects\\game\\src\\images.jpg"));

更新

如果 dis 也不起作用,那么

    jLabel.setIcon(new ImageIcon(getClass().getResource("/image.jpg")));
    jLabel.setText("jLabel");

should.Theimage.jpg应该在您的项目文件夹中。

于 2013-02-01T10:14:24.737 回答
1

我认为您的代码不喜欢您绑定图像的方式。

假设您将图像/图标放在源文件夹中

ImageIcon i=new javax.swing.ImageIcon(getClass().getResource("myimage.jpeg"))

或者如果您在源文件夹中创建一个文件夹

InputStream stream = this.getClass().getClassLoader().getResourceAsStream("/images/image.jpg");
BufferedImage bufferedImage=ImageIO.read(stream);
ImageIcon icon= new ImageIcon(bufferedImage);
于 2013-02-01T10:07:08.617 回答
0

在 IntellijIdea 中。2021 就我而言,它只是没有读取图像文件。要解决这个问题:

1.在项目根目录下创建 res 文件夹('src 的同级文件夹)

2.在文件->项目结构->工件中处理工件,按+,-

3. File->Project Structure->artifacts->output layout 选项卡将最终 jar 的结构设置为“res”文件夹、应用程序根包文件夹(比如“com”)和“META-INF”文件夹。用 yourapp/output 文件夹中的内容和1.步骤“res”中提到的“res”内容填写它们。

4.之后在“项目结构”“模块”中右键单击“资源”并将其标记为资源。

5.像这样声明图像:

ImageIcon loadingLcl = new ImageIcon(this.getClass().getResource("/res/32.gif")); 在放入 JLabel 之前。

此外,最好在初始化应用程序时读取一次图像。否则有时它会抛出 IOException。因此,如果可能的话,在开始时处理它。就像他们在游戏制作中所做的那样。

于 2021-02-16T15:15:44.550 回答