Jump to content
  • Advertisement
Sign in to follow this  
The Hitman

[java] Changing IMageIcon

This topic is 4257 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
×

Important Information

By using GameDev.net, you agree to our community Guidelines, Terms of Use, and Privacy Policy.

We are the game development community.

Whether you are an indie, hobbyist, AAA developer, or just trying to learn, GameDev.net is the place for you to learn, share, and connect with the games industry. Learn more About Us or sign up!

Sign me up!