I'm doing a small GUI program it is that I have two buttons when I press on any of the buttons it displays a dialog box saying which button I pressed .One of the buttons is a text with image displayed on it . my problem is that an exception occurs when the program runs saying NULL pointer exception means it can't reach the image given in IMageIcon how can I solve this problem if I want to display an image from my computer on button and here is code :

Button Frame class

public class ButtonFrame extends JFrame{

    private JButton plainJButton;
    private JButton fancyJButton;

    public ButtonFrame()
        super("Testing Buttons");
        setLayout(new FlowLayout());
         plainJButton=new JButton("Plain Button");

        Icon bug1=new ImageIcon(getClass().getResource("20072011001.jpeg"));
        Icon bug2=new ImageIcon(getClass().getResource("20072011002.jpeg"));
        fancyJButton=new  JButton("Fancy Button",bug1);

        ButtonHandler handler=new ButtonHandler();


    private class ButtonHandler implements ActionListener

        public void actionPerformed(ActionEvent e) {
            JOptionPane.showMessageDialog(ButtonFrame.this,String.format("you pressed %s", e.getActionCommand()));


ButtonFrame buttonFrame=new ButtonFrame();
        buttonFrame.setSize(275, 110);

Recommended Answers

All 4 Replies

have you tried to use

ImageIcon bug1=new ImageIcon("20072011001.jpeg");
        ImageIcon bug2=new ImageIcon("20072011002.jpeg");


Where are the images located? Are they at same folder as the ButtonFrame class file is?

yes they are in the same folder and still I get an exception when I checked out I knew and removed the images so that they're in the same folder but still I get an exception javaAddict :) thnx

well I've solved the problem thank you :)

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, learning, and sharing knowledge.