Display image icon in java
Hi
I am trying to write a code in java, I should be able to create a new image icon using the object. When I try to run the program the image simple does not appear on the button. All the image files are located in the image folder inside the working directory. I am post my code please check it.
Code:
public class Jbt2s extends JFrame {
public static void main(String[] args) {
new Jbt2s();
}
public Jbt2s() {
super("Creating bt2s");
addWindowListener(new ExitListener());
Container cn = getcnPane();
cn.setBackground(Color.white);
cn.setLayout(new FlowLayout());
// This is the statement of interest
// the image can be anything in my
ImageIcon sp = new ImageIcon("images/grapes.jpg");
Jbt2 bt1 = new Jbt2("bt2 1");
cn.add(bt1);
//Jbt2 bt22 = new Jbt2("bt2 2 ",sp);
Jbt2 bt22 = new Jbt2("bt2 2");
cn.add(bt22);
//Jbt2 bt23 = new Jbt2("bt2 3 ", sp);
Jbt2 bt23 = new Jbt2("bt2 3");
bt23.setHorizontalTextPosition(SwingConstants.L EFT);
cn.add(bt23);
//Jbt2 bt24 = new Jbt2(sp);
Jbt2 bt24 = new Jbt2(sp);
cn.add(bt24);
pack();
setVisible(true);
}
}
re: Display image icon in java
Hi,
I went through your code thoroughly, I think you should try this. this may be helpful to your program
Code:
ImageIcon sp = new ImageIcon(this.getClass().getResource("images/grapes.jpg"));
If it does not work then post back again and even if it works then post back with a positive reply.
re: Display image icon in java
Thanks for the reply
I tried you code, and what I got was the following popup.
Code:
Cannot launch Java application
Uncaught exception in main method:
java.lang.NullPointerException
See if you can help me further to solve this. Thank again.
re: Display image icon in java
Hi
Since you are getting a NullPointerException
Code:
NullPointerException
The above is a subclass of
I think it shouldn't cause a compile error. May be there is a bug in your IDE? Check if the IDE is working fine.