aspose file tools*
The moose likes Applets and the fly likes change images in Java Applet Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Applets
Bookmark "change images in Java Applet" Watch "change images in Java Applet" New topic
Author

change images in Java Applet

Billy Bob
Greenhorn

Joined: Jul 10, 2001
Posts: 1
hi... I have an applet using GridBag Layout... what I want to be able to do is when you click on the image, I want it to change to another image... what it is doing right now.. is when you click on the image it keeps the original and creates the new image below it.
Frank Ying
Greenhorn

Joined: Jul 02, 2001
Posts: 5
I have a very similar class that does the image swap, check codes below and c if it helps you.
import java.awt.*;
import java.awt.event.*;
import java.awt.image.*;
import java.net.*;
public class ImageButton extends Canvas {
int w,h;
boolean second;
Image firstimage;
Image secondimage;
public ImageButton(){}
public ImageButton(URL first_b, URL second_b) {
second=false;
InitImage(first_b,second_b);
setSize(w,h);
addMouseListener(new ImageButtonMouseListener());
}
public void InitImage(URL first, URL second) {
MediaTracker tracker;
try {
firstimage = getToolkit().getImage(first);
secondimage = getToolkit().getImage(second);
tracker = new MediaTracker(this);
tracker.addImage(firstimage,0);
tracker.addImage(secondimage,1);
tracker.waitForAll();
}catch (InterruptedException e) {
e.printStackTrace();
}
w=firstimage.getWidth(this);
h=firstimage.getHeight(this);
}
public void paint(Graphics g) {
if (second) {
g.drawImage(secondimage,0,0,this);
}
else
g.drawImage(firstimage,0,0,this);

}
public void setDarkImage(){
if(second){
second = false;
repaint();
}
}
public boolean getSecondState() { return second;}
public int getWidth() { return w;}
public int getHeight() { return h; }
public class ImageButtonMouseListener extends MouseAdapter {
public void mouseClicked(MouseEvent e) {
Point p = e.getPoint();
if ((p.x < w)&&(p.y < h)&&(p.x > 0)&&(p.y > 0)) {
if(second == false){
second = true;
repaint();
}
}
}

}
}
 
Consider Paul's rocket mass heater.
 
subject: change images in Java Applet