Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>You can try this way:</p> <pre><code>ImageIcon icon = new ImageIcon("images/myimage.jpg"); </code></pre> <p>this will work if you have <code>images/myimage.jpg</code> directory in the same folder that you are running your application with your JAR file.</p> <hr> <p>or if you want to use image that is placed <strong>inside</strong> JAR file you can use</p> <pre><code>ImageIcon icon = new ImageIcon(getClass().getResource("images/myimage.jpg")); </code></pre> <p>Don't be afraid when it wont work in IDE. It will work when you run it from JAR file.</p> <hr> <p>Here is some code sample that works for me:</p> <pre><code>import java.io.IOException; import javax.swing.ImageIcon; import javax.swing.JFrame; import javax.swing.JLabel; public class MyFrame extends JFrame { private static final long serialVersionUID = 1L; private JLabel iconLabel; public MyFrame() throws IOException { ImageIcon icon = new ImageIcon(getClass().getResource( "images/myimage.jpg")); iconLabel = new JLabel(icon); getContentPane().add(iconLabel); setSize(icon.getIconWidth(), icon.getIconHeight()); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); setVisible(true); } public static void main(String[] args) throws IOException { new MyFrame(); } } </code></pre> <p>When I try to run it in Eclipse I get </p> <pre><code>Exception in thread "main" java.lang.NullPointerException at javax.swing.ImageIcon.&lt;init&gt;(ImageIcon.java:205) at MyFrame.&lt;init&gt;(MyFrame.java:14) at MyFrame.main(MyFrame.java:25) </code></pre> <p>this Eclipse project looks like </p> <p><img src="https://i.stack.imgur.com/yzIQ2.png" alt="enter image description here"></p> <p>After i export this project to JAR with <code>images</code> folder by</p> <p><code>right-click on project</code> -> <code>Export</code> -> <code>JAR file</code> -> <code>next</code></p> <p><img src="https://i.stack.imgur.com/jdm5N.png" alt="enter image description here"></p> <p><code>next</code> -> <code>next</code> -> <code>select main class</code></p> <p><img src="https://i.stack.imgur.com/U0xuN.png" alt="enter image description here"></p> <p>I double-click created JAR file and see frame with my image:</p> <p><img src="https://i.stack.imgur.com/DLd3F.png" alt="enter image description here"></p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload