How do you change the image in a JPanel?

Hey! (firstly, i need to use image on a JPanel, label&icon not an option).

I've made my JPanel class

publicclass DrawingPanelextends JPanel{

Image img;

DrawingPanel(){

Image img = Toolkit.getDefaultToolkit().getImage("13.jpg");//default image at startup

}

publicvoid paintComponent (Graphics g){

super.paintComponent (g);

// Use the image width & height to find the starting point

int imgX = getSize ().width/2 - img.getWidth (this);

int imgY = getSize ().height/2 - img.getHeight (this);

//Draw image centered in the middle of the panel

g.drawImage (img, 0, 0,this);

}// paintComponent

}// DrawingPanel

And I've made my instance of it and added it to the Frame:

DrawingPanel imagePanel =new DrawingPanel();

Now, I need to change the image on the JPanel according to the user's input. I have the string of the location of the new image. How do I update the JPanel to display this new image? Any help greatly appreciated!!

[1757 byte] By [Tjorriemorriea] at [2007-11-27 9:18:32]
# 1
Found it...move the img variable up one scope and initialize it.then change the img value to the new picture.and just call imagePanel.updateUI();lol, still learning all these classes' methods. Hope this helps someone else in future :)
Tjorriemorriea at 2007-7-12 22:09:54 > top of Java-index,Java Essentials,New To Java...
# 2

Well... You could just add a method in your class which sets the image according to the new image name you provided. Something like this:

public class DrawingPanel extends JPanel {

Image img;

DrawingPanel() {

img = Toolkit.getDefaultToolkit().getImage("13.jpg"); //default image at startup

}

public void setImage(String imageName) {

img = Toolkit.getDefaultToolkit().getImage(imageName); //Loading the desired image

}

public void paintComponent (Graphics g) {

super.paintComponent (g);

// Use the image width & height to find the starting point

int imgX = getSize ().width/2 - img.getWidth (this);

int imgY = getSize ().height/2 - img.getHeight (this);

//Draw image centered in the middle of the panel

g.drawImage (img, 0, 0, this);

} // paintComponent

} // DrawingPanel

laginimaineba at 2007-7-12 22:09:54 > top of Java-index,Java Essentials,New To Java...
# 3
Yes, that works even better. And it's better to make setWhatever methods (or so I read somewhere). Thanks!
Tjorriemorriea at 2007-7-12 22:09:54 > top of Java-index,Java Essentials,New To Java...