• Advertisement
Sign in to follow this  

[java] Changing IMageIcon

This topic is 4111 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

Basicly i want to know how to change the image file of a Image Icon for example example code:
import java.awt.*;
import javax.swing.*;
import java.io.*;
import java.awt.event.*;

public class main extends JFrame {

	String res = "C:/Documents and Settings/Dojo/Desktop/platform/back3.png";
	ImageIcon background = new ImageIcon(res);	


       public void change(){
                  //make image icon change to "C:/Documents and //Settings/Dojo/Desktop/platform/faris.png"
	
	repaint();


	
	public void paint(Graphics g)
	{
		super.paint(g);
		g.drawImage(background.getImage() , 50 , 50,null);
	
	}
	
	public static void main(String[] args){
		main app = new main();
	}
}
so bacsicly i want it so everytime change(); is called the imageicon background changes and it repaints to show it. thankyou. non relevant question: Would photoshop be best choice to learn to create graphics for my game you think?

Share this post


Link to post
Share on other sites
Advertisement
One way you could do it is:


import java.awt.*;
import javax.swing.*;
import java.io.*;
import java.awt.event.*;

public class Main extends JFrame {

private static final String path1 = "C:\\Documents and Settings\\Dojo\\Desktop\\platform\\back3.png";
private static final String path2 = "C:\\Documents and Settings\\Dojo\\Desktop\\platform\\faris.png";

private ImageIcon background1 = new ImageIcon(path1);
private ImageIcon background2 = new ImageIcon(path2);

private ImageIcon currentImage = background1;

public void change() {
if (currentImage == background1) {
currentImage = background2;

} else {
currentImage = background1;
}

repaint();
}

public void paint(Graphics g) {
super.paint(g);

if (currentImage != null) {
g.drawImage(currentImage.getImage(), 50 , 50, null);
}
}

public static void main(String[] args) {
Main app = new Main();
}
}




You should give the variables better names, these are just for example.

Also if you are planning to have lots of different backgrounds this method would not work very well.

Share this post


Link to post
Share on other sites
Sign in to follow this  

  • Advertisement