hello guys, I am trying to add an image to java panel.

I have tried Paint, ImageIcon and every other sort of methods and failed. can someone explain me how do I add an image onto a panel?

thanks for your time.
cheers!

Recommended Answers

All 17 Replies

There are many code samples on this forum. Use Search to find them.
They could use the ImageIO class to read the image from the file and the paintComponent method to draw it on the panel.

JLabel label = new JLabel();
label.setIcon(new ImageIcon(image));

in JPANEL add image as Jlabel.

you can get other solution by simply google it or here daniweb also has similar threads like this...

The code has given by mustafa is right. But it adds only one image to panel. If you need to add multiple images or textboxs and button to panel. You can try this below code.

import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.*;
import javax.swing.*;

public class ImageOnBackground {
    public static void main(String[] args) throws IOException {
        BufferedImage image =
            javax.imageio.ImageIO.read(new File("images/hawk.jpg"));
        ImageBackgroundPanel imp = new ImageBackgroundPanel(image);
        // Set layout and add components to imp as desired.
        addComponents(imp);
        JFrame f = new JFrame();
        f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        f.add(new JScrollPane(imp));
        f.setSize(400,400);
        f.setLocation(200,200);
        f.setVisible(true);
    }

    private static void addComponents(JPanel panel) {
        panel.setLayout(new GridBagLayout());
        GridBagConstraints gbc = new GridBagConstraints();
        gbc.insets = new Insets(20,5,20,5);
        gbc.weightx = 1.0;
        gbc.weighty = 1.0;
        for(int i = 0; i < 10; i++) {
            gbc.gridwidth = ((i+1) % 2 == 0)
                    ? GridBagConstraints.REMAINDER
                    : GridBagConstraints.RELATIVE;
            panel.add(new JButton("button " + (i+1)), gbc);
        }
    }
}

class ImageBackgroundPanel extends JPanel {
    BufferedImage image;

    ImageBackgroundPanel(BufferedImage image) {
        this.image = image;
    }

    protected void paintComponent(Graphics g) {
        super.paintComponent(g);
        g.drawImage(image, 0, 0, this);
    }
}

It was working fine for me.

ok here is what i have done,

import java.*;
import java.awt.*;
import javax.swing.*;
import java.lang.*;

public class theloader extends JFrame
{
	private myui obj;
	
	public theloader()
	{
		obj = new myui();
		setVisible(true);
		setSize(400,400);
		setDefaultCloseOperation(EXIT_ON_CLOSE);
		getContentPane().add(obj);
	}
	
    public static void main(String[] args)
    {
		new theloader();
    }
}

theloader.java

import java.*;
import java.awt.*;
import javax.swing.JButton;
import javax.swing.ImageIcon;
import javax.swing.*;
import java.awt.event.*;

class myui extends JPanel
{
	private JPanel thepanel;
	private JPanel toppanel;
	private JButton abutton;
	private JPanel bottompanel;
	private JLabel imagelabel; 
		
	public myui()
    	{
   		Init();
    	}

	public void Init()
	{
    		thepanel = new JPanel();
    		bottompanel = new JPanel();
    		toppanel = new JPanel();
    		abutton = new JButton("click");
		thepanel.setLayout(new FlowLayout());
		bottompanel.setLayout(new FlowLayout());
		toppanel.setLayout(new FlowLayout());
		bottompanel.add(abutton);
		imagelabel.setIcon(new ImageIcon(getClass().getResource("C:/Users/dw106/Desktop/wait.jpg")));
		toppanel.add(abutton);
		bottompanel.add(imagelabel);
		thepanel.add(toppanel);
		thepanel.add(bottompanel);
	}
               
}

myui.java

i dont know whats the problem here, but this isnt working for me :(

Move the setVisible(true) to after you have finished setting up the gui.

OK, I have added setVisible(true) in Init(); I still get the NPE :(
and when I remove the image code from my program, It refuses to run. and when I put back the setVisible(true) in myui.java the app runs
without any problem.

Exception in thread "main" java.lang.NullPointerException
    at javax.swing.ImageIcon.<init>(ImageIcon.java:167)
    at myui.renderLayout(myui.java:82)
    at myui.<init>(myui.java:35)
    at theloader.<init>(theloader.java:21)
    at theloader.main(theloader.java:32)

Process completed.

it gives this message and it quits.

The error trace doesn't match the code you posted. For example
theloader code you posted doesn't have 32 lines.

at theloader.main(theloader.java:32)

and myui doesn't have 82 lines

at myui.renderLayout(myui.java:82)

It's hard to help if your real code is different from what is posted.

A suggestion - do this in three steps and test the results between each step:
imagelabel.setIcon(new ImageIcon(getClass().getResource("C:/Users/dw106/Desktop/wait.jpg")));

ok here is my code...

/**
 * @(#)loader.java
 *
 *
 * @author 
 * @version 1.00 2010/6/24
 */
package uniKEY;

import java.*;
import java.awt.*;
import javax.swing.*;
import java.lang.*;

public class loader extends JFrame
{
	private ui _uiobj;
	
	public loader()
	{
		_uiobj = new ui();
		setSize(180,300);
		setTitle("UniKEY");
		setDefaultCloseOperation(EXIT_ON_CLOSE);
		setLocationRelativeTo(null);
		setResizable(false);
		setVisible(true);
		getContentPane().add(_uiobj);
	}
	
    public static void main(String[] args)
    {
		new loader();
    }
}

loader.java

/**
 * @(#)ui.java
 *
 *
 * @author 
 * @version 1.00 2010/6/24
 */

package uniKEY;
import java.*;
import java.awt.*;
import javax.swing.JButton;
import javax.swing.ImageIcon;
import javax.swing.*;
import java.awt.event.*;
import java.io.*;

class ui extends JPanel implements ActionListener
{
	private JPanel _mainpanel;
	private JPanel _lightpanel;
	private JButton _button[];
	private JPanel _keypadpanel;
	private String _dbPass;
	private String _userPass;
	private String _clickValue;
	private int _click = 0;
	private JLabel _imagelabel; 
	private ImageIcon _myImage;
    private String _mypath;
    
    public ui()
    {
    	_clickValue= null;
		_userPass= null;
    	loadDB();
   		renderLayout();
   		renderFrame();
    }

	public void renderLayout()
	{
    	_mainpanel = new JPanel();
    	_keypadpanel = new JPanel();
    	_lightpanel = new JPanel();
    	_button = new JButton[12];
		_mainpanel.setLayout(new BorderLayout());
		_keypadpanel.setLayout(new GridLayout(4,3,0,0));
		_lightpanel.setLayout(new FlowLayout());
						
		for (int i=0; i<=9; i++)
		{
			_button[i]= new JButton(String.valueOf(i));
			_button[i].setPreferredSize(new Dimension(55,55));
		}
		
		_button[10] = new JButton("*");
		_button[0] = new JButton("0");
		_button[11] = new JButton("#");
		
		for (int i=1; i<=3; i++)
		{
			_keypadpanel.add(_button[i]);	 	
		}

		for (int i=4; i<=6; i++)
		{
			_keypadpanel.add(_button[i]);	 	
		}
		
		for (int i=7; i<=9; i++)
		{
			_keypadpanel.add(_button[i]);	 	
		}

		_keypadpanel.add(_button[10]);
		_keypadpanel.add(_button[0]);
		_keypadpanel.add(_button[11]);
		
		for(int i=0;i<12;i++)
		{
			_button[i].addActionListener(this);
		}
		
		_mypath = "C:/Users/sunny/Desktop/wait.jpg";
		_myImage = new ImageIcon(getClass().getResource(_mypath));
		_imagelabel.setIcon(_myImage);
		_lightpanel.add(_imagelabel);
	}
	
    public void renderFrame()
    {
		_mainpanel.add(_keypadpanel,BorderLayout.NORTH);
		_mainpanel.add(_lightpanel,BorderLayout.SOUTH);
		this.add(_mainpanel);
    }
    
	public void loadDB()
	{
		try
		{
			FileInputStream _fis = new FileInputStream("C:/Users/sunny/Desktop/myfile.txt"); 
			DataInputStream _dis = new DataInputStream(_fis);
			BufferedReader _br = new BufferedReader(new InputStreamReader(_dis));
			_dbPass=_br.readLine();
			_dis.close();
		}
		catch(Exception e)
		{
			JOptionPane.showMessageDialog(_mainpanel,"Error Occoured!\n"+e.getMessage()+"\n");
			System.exit(0);
		}
			
	}
	
    private void check()
	{
		if(_userPass.equals(_dbPass))
		{
			_click=0;
			JOptionPane.showMessageDialog(_mainpanel,"Access Granted!");
		}
		else
		{
			_click=0;
			JOptionPane.showMessageDialog(_mainpanel,"Access Denied!");
		}
	}
	private void reportError()
	{
		JOptionPane.showMessageDialog(_mainpanel,"An Error Occoured!\nThe Application needs to be restarted!\n");
		System.exit(0);
	}
    private void processInput(String _value)
	{
		if(_click==0)
		{
			_userPass=_value;
			_click++;
		}
		else if(_click>0)
		{
			_userPass+=_value;
			_click++;
		}
	}
                
    public void actionPerformed(ActionEvent e)
	{
    	if(e.getSource() == _button[0])
    	{
    		_clickValue = _button[0].getText();
    		if(_click < 3)
    		{
    			processInput(_clickValue);
			}
    		else if(_click ==3) 
    		{
    			processInput(_clickValue);
    			check();	
			}
			else
			{
				reportError();
			}
    	}
		else if(e.getSource() == _button[1])
    	{
    		_clickValue = _button[1].getText();
    		if(_click <3)
    		{
    			processInput(_clickValue);
			}
    		else if(_click ==3) 
    		{
    			processInput(_clickValue);
    			check();	
			}
			else
			{
				reportError();
			}
		}
    	else if(e.getSource() == _button[2])
    	{
    		_clickValue = _button[2].getText();
    		if(_click <3)
    		{
    			processInput(_clickValue);
			}
    		else if(_click ==3) 
    		{
    			processInput(_clickValue);
    			check();	
			}
			else
			{
				reportError();
			}
    	}
		else if(e.getSource() == _button[3])
    	{
    		_clickValue = _button[3].getText();
    		if(_click <3)
    		{
    			processInput(_clickValue);
			}
    		else if(_click ==3) 
    		{
    			processInput(_clickValue);
    			check();	
			}
			else
			{
				reportError();
			}
    	}
    	else if(e.getSource() == _button[4])
    	{
    		_clickValue = _button[4].getText();
    		if(_click <3)
    		{
    			processInput(_clickValue);
			}
    		else if(_click ==3) 
    		{
    			processInput(_clickValue);
    			check();	
			}
			else
			{
				reportError();
			}
    	}
    	else if(e.getSource() == _button[5])
    	{
    		_clickValue = _button[5].getText();
    		if(_click <3)
    		{
    			processInput(_clickValue);
			}
    		else if(_click ==3) 
    		{
    			processInput(_clickValue);
    			check();	
			}
			else
			{
				reportError();
			}
    	}
    	else if(e.getSource() == _button[6])
    	{
    		_clickValue = _button[6].getText();
    		if(_click <3)
    		{
    			processInput(_clickValue);
			}
    		else if(_click ==3) 
    		{
    			processInput(_clickValue);
    			check();	
			}
			else
			{
				reportError();
			}
    	}
    	else if(e.getSource() == _button[7])
    	{
    		_clickValue = _button[7].getText();
    		if(_click <3)
    		{
    			processInput(_clickValue);
			}
    		else if(_click ==3) 
    		{
    			processInput(_clickValue);
    			check();	
			}
			else
			{
				reportError();
			}
    	}
    	else if(e.getSource() == _button[8])
    	{
    		_clickValue = _button[8].getText();
    		if(_click <3)
    		{
    			processInput(_clickValue);
			}
    		else if(_click ==3) 
    		{
    			processInput(_clickValue);
    			check();	
			}
			else
			{
				reportError();
			}
    	}
    	else if(e.getSource() == _button[9])
    	{
    		_clickValue = _button[9].getText();
    		if(_click <3)
    		{
    			processInput(_clickValue);
			}
    		else if(_click ==3) 
    		{
    			processInput(_clickValue);
    			check();	
			}
			else
			{
				reportError();
			}
    	}
    	else if(e.getSource() == _button[10])
    	{
    		_clickValue = _button[10].getText();
    		if(_click <3)
    		{
    			processInput(_clickValue);
			}
    		else if(_click ==3) 
    		{
    			processInput(_clickValue);
    			check();	
			}
			else
			{
				reportError();
			}
    	}
    	else if(e.getSource() == _button[11])
    	{
    		_clickValue = _button[11].getText();
    		if(_click <3)
    		{
    			processInput(_clickValue);
			}
    		else if(_click ==3) 
    		{
    			processInput(_clickValue);
    			check();	
			}
			else
			{
				reportError();
			}
    	}
		else
    	{
			reportError();    			
		}
	}
}

I've tried writing a println just above where the error occours, it still shows me a NPE..

--------------------Configuration: uniKEY - JDK version 1.6.0_20 <Default> - <Default>--------------------
Exception in thread "main" java.lang.NullPointerException
    at javax.swing.ImageIcon.<init>(ImageIcon.java:167)
    at uniKEY.ui.renderLayout(ui.java:86)
    at uniKEY.ui.<init>(ui.java:37)
    at uniKEY.loader.<init>(loader.java:21)
    at uniKEY.loader.main(loader.java:33)

Process completed.

This appears to be the statement at line 82

_button.addActionListener(this);

What is the value of i when this this statement causes a NPE?
To detect this, add a System.out.println("i=" + i) statement in from of line 82
Do all the elements in _button[] have values?

Finding a variable with a null value is very simple. The error message gives you the line number. You have to look at that line of code in your program and see why the variable there is null.

Hi norm, I dont see any errors on line number 82, I have an error on line number 86.
and when I write the println statement above line 82 I get this

--------------------Configuration: uniKEY - JDK version 1.6.0_20 <Default> - <Default>--------------------
i =0
i =1
i =2
i =3
i =4
i =5
i =6
i =7
i =8
i =9
i =10
i =11

the value of i is an integer and not null.. what do I do now?

I can't help you if you don't post the code that goes with the error messages. The error message you posted shows line 82:

Exception in thread "main" java.lang.NullPointerException
at javax.swing.ImageIcon.<init>(ImageIcon.java:167)
at myui.renderLayout(myui.java:82)
at myui.<init>(myui.java:35)
at theloader.<init>(theloader.java:21)
at theloader.main(theloader.java:32)

I have an error on line number 86.

Where is the full text of the error message?

Check that there is valid URL for the ImageIcon constructor.

Check that there is valid URL for the ImageIcon constructor.

yep the path for the file is valid. The file exists, and I can open the file by pasting the path in start > run

dont know why java is showing it a null :/

ok I have used this

_mypath = "C:/Users/sunny/Desktop/wait.jpg";
	_myImage = new ImageIcon(_mypath);

instead of this

_mypath = "C:/Users/sunny/Desktop/wait.jpg";
        _myImage = new ImageIcon(getClass().getResource(_mypath));

and one of the NPE vanished..
Lovely!

now, coming to the other error, it says that there is an error at renderLayout();
what error can it be? Its a custom function which doesnt return or hold any values.

showing it a null

What is null?????
Why is it null????

Don't use 'it' in your posts. Give a FULL explanation.

it says that there is an error at renderLayout();

ok, I've done some googling and fixed the problem myself.

so far this is my new ui.java

/**
 * @(#)ui.java
 *
 *
 * @author 
 * @version 1.00 2010/6/24
 */

package uniKEY;
import java.*;
import java.awt.*;
import java.awt.image.*;
import javax.swing.JButton;
import javax.swing.ImageIcon;
import javax.swing.*;
import java.awt.event.*;
import java.io.*;

class ui extends JPanel implements ActionListener
{
	private JPanel _mainpanel;
	private JPanel _lightpanel;
	private JButton _button[];
	private JPanel _keypadpanel;
	private String _dbPass;
	private String _userPass;
	private String _clickValue;
	private int _click = 0;
	private JLabel _imagelabel; 
	private ImageIcon _myImage;
    private String _mypath;
    
    public ui()
    {
    	_clickValue= null;
		_userPass= null;
    	loadDB();
   		renderLayout();
   		renderFrame();
    }

	public void renderLayout()
	{
    	_mainpanel = new JPanel();
    	_keypadpanel = new JPanel();
    	_lightpanel = new JPanel();
    	_button = new JButton[12];
		_mainpanel.setLayout(new BorderLayout());
		_keypadpanel.setLayout(new GridLayout(4,3,0,0));
		_lightpanel.setLayout(new FlowLayout());
						
		for (int i=0; i<=9; i++)
		{
			_button[i]= new JButton(String.valueOf(i));
			_button[i].setPreferredSize(new Dimension(55,55));
		}
		
		_button[10] = new JButton("*");
		_button[0] = new JButton("0");
		_button[11] = new JButton("#");
		
		for (int i=1; i<=3; i++)
		{
			_keypadpanel.add(_button[i]);	 	
		}

		for (int i=4; i<=6; i++)
		{
			_keypadpanel.add(_button[i]);	 	
		}
		
		for (int i=7; i<=9; i++)
		{
			_keypadpanel.add(_button[i]);	 	
		}

		_keypadpanel.add(_button[10]);
		_keypadpanel.add(_button[0]);
		_keypadpanel.add(_button[11]);

		for(int i=0;i<12;i++)
		{
			_button[i].addActionListener(this);
		}
		setImage("wait");
	}

	private void setImage(String param)
	{
		_mypath = "C:/Users/sunny/Desktop/"+param+".jpg";
		_myImage = new ImageIcon(_mypath);
		_imagelabel = new JLabel(resizeImage(_myImage));
		_lightpanel.add(_imagelabel);		
	}
	
	private ImageIcon resizeImage(ImageIcon _myImage)
	{
		Image _img = _myImage.getImage();
		Image _newimg = _img.getScaledInstance(50, 38,Image.SCALE_SMOOTH); 
		ImageIcon _newIcon = new ImageIcon(_newimg); 
		return _newIcon;
	}
    
    public void renderFrame()
    {
		_mainpanel.add(_keypadpanel,BorderLayout.NORTH);
		_mainpanel.add(_lightpanel,BorderLayout.SOUTH);
		this.add(_mainpanel);
    }
    
	public void loadDB()
	{
		try
		{
			FileInputStream _fis = new FileInputStream("C:/Users/sunny/Desktop/myfile.txt"); 
			DataInputStream _dis = new DataInputStream(_fis);
			BufferedReader _br = new BufferedReader(new InputStreamReader(_dis));
			_dbPass=_br.readLine();
			_dis.close();
		}
		catch(Exception e)
		{
			JOptionPane.showMessageDialog(_mainpanel,"Error Occoured!\n"+e.getMessage()+"\n");
			System.exit(0);
		}
			
	}
	
    private void check()
	{
		if(_userPass.equals(_dbPass))
		{
			_click=0;
			JOptionPane.showMessageDialog(_mainpanel,"Access Granted!");
			setImage("go");
		}
		else
		{
			_click=0;
			JOptionPane.showMessageDialog(_mainpanel,"Access Denied!");
			setImage("stop");
		}
	}
	private void reportError()
	{
		JOptionPane.showMessageDialog(_mainpanel,"An Error Occoured!\nThe Application needs to be restarted!\n");
		System.exit(0);
	}
    private void processInput(String _value)
	{
		if(_click==0)
		{
			_userPass=_value;
			_click++;
		}
		else if(_click>0)
		{
			_userPass+=_value;
			_click++;
		}
	}
                
              //// and the rest of the code..... goes there....
}

ui.java

now I have made 2 methods in it, one of them resizes the image, and the second loads up the image. All I have to do is to, change the image at runtime.

can anyone point me how do achieve this?
thanks.

Be a part of the DaniWeb community

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