当前位置: 动力学知识库 > 问答 > 编程问答 >

netbeans - Java Hello World App Does Nothing on Launch When Image Displayed

问题描述:

I've got a small "hello world" app I've created, using JFrame/JPanel, and it works flawlessly inside my IDE (Netbeans). I tested it with just drawing a string to the screen using Graphics.drawString(), and it worked perfectly both in the browser, and in the built .Jar file.

I decided to add in an image just to test it out (I'm new to Java), and the App continued to function inside the IDE, but the built .Jar file doesn't launch anything, or give an error or anything.

Here are the 2 class files:

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

}

}

If I comment out

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

and

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

it continues to work perfectly.

I've tried to figure this out myself, I can't find anything via google or stack overflow. It is a difficult search phrase to craft.

Anyone have any ideas why this would run in NetBeans, but not as a standalone .Jar?

网友答案:

Your issue is in this line

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

The "../images.LKRZV.jpg" path is correct when you're running in NetBeans, but it isn't correct when you run your JAR. Make sure you provide a provide a path that is correct relative to your jar file's location. If you change that path to the absolute path of your image, your program should work correctly. It would probably be better to pack the image in with the jar.

分享给朋友:
您可能感兴趣的文章:
随机阅读: