Ekrem Solmaz
Ekrem Solmaz

Reputation: 707

I can't add Image to a JButton in Java

import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JButton;
import javax.swing.ImageIcon;
import javax.swing.Icon;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import java.awt.FlowLayout;


public class Gui extends JFrame{


private JButton normal;
private JButton custom;

public Gui(){
    super("button program");
    setLayout(new FlowLayout());
    Icon b=new ImageIcon(getClass().getResource("C:\\temp\\image\\b.jpg"));

    custom=new JButton("custom",b);
    add(custom);
}
}

and I got this error:

Exception in thread "main" java.lang.NullPointerException at javax.swing.ImageIcon.(Unknown Source) at Gui.(Gui.java:22) at test.main(test.java:7)

I tried putting image in src, doesn't work too.

Upvotes: 1

Views: 827

Answers (2)

Flood2d
Flood2d

Reputation: 1358

You cannot load external files like 'C:\test\image\b.jpg' by using getClass().getResource(...).

But ImageIcon as a nice constructor that loads an image from is path. Use something like this instead:

Icon b = new ImageIcon("C:\\temp\\image\\b.jpg");

Upvotes: 1

hicham abdedaime
hicham abdedaime

Reputation: 366

You can cerate pakage in application and store icon to this package com.icon

example for add icon to jbutton:

button.setIcon(new ImageIcon(MyFrame.class.getResource("com/icon/Ok.png")));

Upvotes: 0

Related Questions