我有一个使用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);
它继续完美地工作。
我试图自己解决这个问题,我无法通过Google或堆栈溢出找到任何东西。这是一个很难编写的搜索短语。
任何人都知道为什么它将在NetBeans中运行,但不能作为独立的.Jar运行吗?
最佳答案
您的问题在这一行
this.hello_image = new ImageIcon(Board.class.getResource("../images/LKRZV.jpg")).getImage();
在NetBeans中运行时,“ ../ images.LKRZV.jpg”路径正确,但在运行JAR时,路径不正确。确保您提供的路径相对于jar文件的位置是正确的。如果您将该路径更改为图像的绝对路径,则程序应该可以正常运行。将图像与罐子包装在一起可能会更好。