Sign in to follow this  
The Hitman

[java] Changing IMageIcon

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
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

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this