gpt4 book ai didi

显示图像时 Java Hello World 应用程序启动时不执行任何操作

转载 作者:行者123 更新时间:2023-12-01 17:30:09 25 4
gpt4 key购买 nike

我使用 JFrame/JPanel 创建了一个小型“hello world”应用程序,它在我的 IDE (Netbeans) 中完美运行。我仅使用 Graphics.drawString() 在屏幕上绘制字符串进行了测试,它在浏览器和构建的 .Jar 文件中都完美运行。

我决定添加一个图像只是为了测试它(我是 Java 新手),并且该应用程序继续在 IDE 中运行,但构建的 .Jar 文件不会启动任何内容,或者给出错误或任何东西。

这是 2 个类文件:

Boxy_Main.java:

package boxy;

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

public class Boxy_Main extends JFrame {

public static Boxy_Main main;

public Boxy_Main() {
add(new Board());
setTitle("Boxy");
setDefaultCloseOperation(EXIT_ON_CLOSE);
setSize(467, 700);
setLocationRelativeTo(null);
setVisible(true);
setResizable(true);
}
public static void main(String[] args) {
main = new Boxy_Main();
}
}

Board.java:

package boxy;

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

public class Board extends JPanel {

public Graphics2D g2d;
public Graphics g;
public Image hello_image;

public Board() {

this.set_properties();

}

public void set_properties() {

this.hello_image = new ImageIcon(Board.class.getResource("../images/LKRZV.jpg")).getImage();


}

public void paint(Graphics g) {

this.g = g;
this.g2d = (Graphics2D) g;


this.g2d.drawImage(this.hello_image, null, this);

this.g.drawString("hello", 100, 80);
this.g.drawString("world", 100, 94);


}
}

如果我注释掉

this.hello_image = new ImageIcon(Board.class.getResource("../images/LKRZV.jpg")).getImage();

this.g2d.drawImage(this.hello_image, null, this);

它继续完美地工作。

我试图自己解决这个问题,但我无法通过谷歌或堆栈溢出找到任何东西。这是一个很难制作的搜索短语。

有人知道为什么它可以在 NetBeans 中运行,而不是作为独立的 .Jar 运行吗?

最佳答案

您的问题在这一行

this.hello_image = new ImageIcon(Board.class.getResource("../images/LKRZV.jpg")).getImage();

当您在 NetBeans 中运行时,“../images.LKRZV.jpg”路径是正确的,但当您运行 JAR 时,它就不正确。确保您提供的路径相对于您的 jar 文件的位置是正确的。如果您将该路径更改为图像的绝对路径,您的程序应该可以正常工作。将图像与 jar 一起打包可能会更好。

关于显示图像时 Java Hello World 应用程序启动时不执行任何操作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11870914/

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