hi, does anyone know how to insert a background picture to a JPanel?
I have googled around, found something seem more difficult than it should be, and a simple one as below but not showing the pic.

midBoard = new JPanel();
		JLabel pic = new JLabel(new ImageIcon("Sunset.jpg"));
		//midBoard.setBackground(java.awt.Color.RED);
		midBoard.add(pic);

any suggestion? thanks

The easiest way to do this is to extend JPanel and override the paintComponent method. When you override the paintComponent method, you should do the following:

public void paintComponent( Graphics g )
{
  super.paintComponent( g );
  Graphics2D g2d = (Graphics2D) g;
  // use g2d.drawImage methods to paint your background image here...
}

thanks, however, the drawImage() method has many parameters. would you mind to show how i import just one image to the drawImage()?

i got it so far :

import java.text.MessageFormat;
import java.sql.*;
import javax.swing.*;
import javax.swing.ImageIcon;
import java.awt.*;
import java.awt.event.*;
import java.awt.print.*;


public class TheFrame extends JFrame
{
	private JMenuBar mb;
	private JPanel midBoard;
	private JPanel textPan;	
	private BorderLayout bl = new BorderLayout();
	
	public TheFrame()
	{
		super("****** Employee Record Program @@ Written by Henry Li ******");
		this.setLayout(bl);
		mb = new MenuBar(this);
		
		
		/////////////// middle board //////////////////////
		//midBoard = new JPanel();
		midBoard = new MidPic();  // ???????????  
		
		
		//JLabel pic = new JLabel(new ImageIcon("Sunset.jpg"));
		//midBoard.setBackground(java.awt.Color.RED);
		//midBoard.add(pic);
		

		////////// end middle board //////////////////
	
		
		////////////  the credit message ////////////////
		JLabel one = new JLabel("Java Final Project: Employee Record");
		one.setAlignmentX(0.5f);
		
		JLabel two = new JLabel("Written by Henry Li");
		two.setAlignmentX(0.5f);
		
		textPan = new JPanel();
		textPan.setBackground(java.awt.Color.gray);
		LayoutManager boxLayout = new BoxLayout(textPan, BoxLayout.Y_AXIS);
		
		textPan.setLayout(boxLayout);
		textPan.setSize(100,300);
		textPan.add(one);
		textPan.add(two);
		//////////// end the center message ////////////////
		
	
		///////////// The Frame setup /////////////////
		
		setJMenuBar(mb);                         // NORTH of Frame
		add(midBoard, BorderLayout.CENTER);     //  CENTER of Frame
		add(textPan, BorderLayout.SOUTH);      //   SOUTH of Frame
		validate();
		
		setBounds(400, 400, 600, 300);
		setVisible(true);
		//////////////  end frame setup ////////////////
	}
	
	


	public static void main(String arg[]) throws SQLException
	{
		new TheFrame();
	}

	
}// end the Class TheFrame

    
  	class MidPic extends JPanel
  	{
  		public void paintComponent (Graphics g)
  		{
  			super.paintComponent(g);
  			Graphics2D g2d = (Graphics2D) g;
  			g2d.drawImage("Sunset.jpg");
  		}
  	}

thanks

found a similar example and implemented,, pic now showing still.

anything missing ?

import java.text.MessageFormat;
import java.sql.*;
import javax.swing.*;
import javax.swing.ImageIcon;
import java.awt.*;
import java.awt.event.*;
import java.awt.print.*;


public class TheFrame extends JFrame
{
	private JMenuBar mb;
	private JPanel midBoard;
	private JPanel textPan;	
	private BorderLayout bl = new BorderLayout();
	private ImageIcon icon;
	private Image image;
	
	public TheFrame()
	{
		super("****** Employee Record Program @@ Written by Henry Li ******");
		this.setLayout(bl);
		mb = new MenuBar(this);
		mb.setBackground(java.awt.Color.white);
		
		
		
		
		
		
		
		/////////////// middle board //////////////////////
		
		icon = new ImageIcon("Sunset.jpg");
		
		JPanel panel = new JPanel()
		{
			
			
			protected void paintComponent(Graphics g)
			{
				g.drawImage(icon.getImage(), 0,0, null);
				super.paintComponent(g);
			}
		};
		
		panel.setOpaque(false);
		panel.setPreferredSize(new Dimension(100, 100));
		
		
		
		//////////// end mid board  //////////////
		
		
		
		
		
		////////////  the credit message ////////////////
		JLabel one = new JLabel("Java Final Project: Employee Record");
		one.setAlignmentX(0.5f);
		
		JLabel two = new JLabel("Written by Henry Li");
		two.setAlignmentX(0.5f);
		
		textPan = new JPanel();
		textPan.setBackground(java.awt.Color.white);
		LayoutManager boxLayout = new BoxLayout(textPan, BoxLayout.Y_AXIS);
		
		textPan.setLayout(boxLayout);
		textPan.setSize(100,300);
		textPan.add(one);
		textPan.add(two);
		//////////// end the center message ////////////////
		
	
		///////////// The Frame setup /////////////////
		
		setJMenuBar(mb);                         // NORTH of Frame
		//add(midBoard, BorderLayout.CENTER);     //  CENTER of Frame
		add(panel, BorderLayout.CENTER);
		add(textPan, BorderLayout.SOUTH);      //   SOUTH of Frame
		validate();
		
		setBounds(400, 400, 600, 300);
		setVisible(true);
		//////////////  end frame setup ////////////////
	}
	
	


	public static void main(String arg[]) throws SQLException
	{
		new TheFrame();
	}

	
}// end the Class TheFrame

I think you're probably having a resource location issue. Take a look through this info on loading images with getResource():http://java.sun.com/docs/books/tutorial/uiswing/components/icon.html#getresource

haha, ezzaral... you are just too good every time.. hit right at the point. right, i just figured it out i should have placed my image somewhere other than where i placed it. thanks for reply very much though.

if you don't mind, i do have one other thing would ask for a quick opinion. basically i have buttons and actionListeners... .now i wanna add my KeyListener as well... how do i place the event codes in both the ActionListener and KeyListener without repeating the long code twice?

//import java.text.MessageFormat;
//import java.util.*;
import javax.swing.*;
//import java.awt.*;
import java.awt.event.*;

public class AddRecord implements ActionListener
{
	private JFrame frame;
	private RecordCP cp;
	private JButton addButton, dummyButton;
	
	private DataHolder dh = new DataHolder();
	private boolean status=true;
	int id, age;
	String fn, ln, ph, add, city, st, zip, sex;
	double hourly, hours;
	
	
	public AddRecord(JFrame f)
	{
		frame = f;
		cp = new RecordCP(f);  //this is a JPanel with the form
		
		addButton= new JButton("Add Record");
		addButton.addActionListener(this);
		
		addButton.addKeyListener(new KeyAdapter()
		{
			public void keyPressed(KeyEvent e)
			{
				if(e.getKeyCode()== KeyEvent.VK_ENTER)
				{
					JOptionPane.showMessageDialog(null, "Can't figure this out unless duplicating the same code of ActionEvent.");
				}
			}
		});
		
		dummyButton = new JButton("");
		
		cp.add(addButton);
		cp.add(dummyButton);
	}
	
	
	public void actionPerformed(ActionEvent e)
	{
		wrapper(e);
		
	} // end function actionPerformed
		
	
	private void wrapper(ActionEvent e)
	{
		frame.getContentPane().removeAll();
		cp.setBounds(400, 400, 400, 200);
		cp.setVisible(true);
		frame.add(cp);
		frame.validate();
	    frame.setVisible(true);
	    frame.repaint();
		
		if((e.getSource() == addButton))
		{
			try
			{
				if(cp.getFields().get(0).equals(""))
				{
					JOptionPane.showMessageDialog(null, "Employee ID must be entered!");
					status=false;
				}
			
				else
				{
					
					id = new Integer(cp.getFields().get(0));
					
					boolean existID = dh.idCheck(id);
					
					if(existID ==true)
					{
				
						JOptionPane.showMessageDialog(null, "The ID is already exist.");
						status=false;
					}
					else
					{
						fn = cp.getFields().get(1);
						ln = cp.getFields().get(2);
						ph = cp.getFields().get(3);
						add = cp.getFields().get(4);
						city= cp.getFields().get(5);
						st = cp.getFields().get(6);
						zip = cp.getFields().get(7);
						sex = cp.getFields().get(9);
						
				
						if(cp.getFields().get(8).equals(""))
						{
							age=0;
						}
			
						else
						{
							age = new Integer(cp.getFields().get(8));
						}	
			
						if(cp.getFields().get(10).equals(""))
						{
							hourly= 0;
						}
			
						else
						{
							hourly = new Double(cp.getFields().get(10));
						}
			
						if(cp.getFields().get(11).equals(""))
						{
							hours=0;
						}
			
						else
						{	
							hours = new Double(cp.getFields().get(11));
						}
						
						status = true;
					}// end ID check else
					
					
					if(status == true)
					{
						dh.addRecord(id, fn, ln, ph, add, city, st, zip, age, sex, hourly, hours);
						cp.clearFields();
						JOptionPane.showMessageDialog(null, "The new record has been saved!");
						dh.shutDown();
					}
				}// if id field has something --> the else
			}//end try
			
			catch(NumberFormatException nfe)
			{
				JOptionPane.showMessageDialog(null, "Please enter number only for Employee ID, age, hourly rate, and hours. Thank you");
			}
		}//end addButton
	} // end wrapper
	
	
} // end class AddRecord

i got everything into a method ... and i tried something like this

method(ActionEvent a, KeyEvent k)
{   
     if (e.getSource() == button || k.getSource() == button)
}

not working.. huh, please shed some light on this one.

... but if all you want to do is have a default button clicked when you press "enter", see getRootPane and setDefaultButton in the Swing API

And the unofficial way would be to put the code in a method, then call the method in the appropriate places.

Anyone still reading this after 7 years...

Don't use the code referred to in the previous post - it reloads the image resource every time the panel is repainted. That's really stupid.

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.