• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

change images in Java Applet

 
Billy Bob
Greenhorn
Posts: 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 5
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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();
}
}
}

}
}
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic