I am using eclipse and I want to add a image onto a label or a logo for my GUI.
I want it to LOOK LIKE THIS!
I uploaded it onto the web because I dont have 10 reputation.
(Names cool program) is the image
import java.awt.*;
import javax.swing.*;
import javax.swing.JFrame;
public class MainClass extends JFrame{ // super class JFrame
// Kind of a tutorial for creating GUI's in java
private JLabel label;
private JLabel label1;
private JButton button;
private JTextField textfeild;
private ImageIcon image1; // image for my logo
public MainClass () {
setLayout (new FlowLayout());
image1 = new ImageIcon (getClass ().getResource ("logo.gif")); // declares image
label = new JLabel ("This is the label");
add (label);
label1 = new JLabel (image1); // adds image
add (label1);
textfeild = new JTextField (15);
add (textfeild);
button = new JButton ("Click");
add (button);
}
public static void main(String[] args) {
MainClass gui = new MainClass ();
gui.setDefaultCloseOperation (JFrame.EXIT_ON_CLOSE); // creates window
gui.setSize (300,300);
gui.setVisible (true);
gui.pack ();
gui.setTitle ("Title");
}
}
Program compiles but doesn't run. Gives me
Exception in thread "main" java.lang.NullPointerException
at javax.swing.ImageIcon.<init>(Unknown Source)
at JonsCalc.<init>(JonsCalc.java:18)
at JonsCalc.main(JonsCalc.java:38)
This piece of code getClass().getResource ("logo.gif")
means that the image should be loaded from the same location as your class MainClass
has. Check that you image is in the same package as MainClass. If you use Eclipse, than put image file in the package in src
folder, it will be copied to bin
automatically.