Win a copy of Programmer's Guide to Java SE 8 Oracle Certified Associate (OCA) this week in the OCAJP forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

placing images in applets

 
David Record
Greenhorn
Posts: 7
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
how do I place an image in an applet like a jpeg or gif, and have the applet place the image where I click the mouse?
thanks guys
 
Frank Ying
Greenhorn
Posts: 5
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You can use my ImageLoader program:
import java.awt.*;
import java.awt.event.*;
import java.awt.image.*;
import java.net.*;
public class ImageLoader extends Canvas {
Image image;
int w;
int h;
public ImageLoader(){}
public ImageLoader(URL i) {
load(i);
}
public void load(URL url) {
MediaTracker tracker;
try {
image = getToolkit().getImage(url);
tracker = new MediaTracker(this);
tracker.addImage(image,0);
tracker.waitForID(0);
}catch (InterruptedException e) {
e.printStackTrace();
}
w=image.getWidth(this);
h=image.getHeight(this);
setSize(w,h);
}
public void paint(Graphics g) {
g.drawImage(image,0,0,this);
}
public int getWidth() { return w; }
public int getHeight() { return h; }
}
In your calling applet, put the following code:
ImageButton btnEntry = new ImageButton
(new URL(getCodeBase(), "off_entry.gif"),
new URL(getCodeBase(), "on_entry.gif"));
add(btnEntry);
btnEntry.setBounds(0,0,145,21);
Hope that works on your program.
Frank
 
David Record
Greenhorn
Posts: 7
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
hey thanks I'll give it a shot and get back to you.
 
David Record
Greenhorn
Posts: 7
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
THis is what I have so far, and I'm getting an instantiation error.
//<applet code="AppletApp.class" width=200 height=300></applet>
import java.awt.*; //<-- added code
import java.applet.*; //<-- added code
import java.awt.event.*; //<-- added code
abstract class AppletApp extends Applet implements MouseListener{

private Image duke;
private int xPos,yPos;

public void init() {

duke = getImage(getDocumentBase(),"duke.gif");

addMouseListener( this );

}
public void paint(Graphics g) {

setBackground(Color.white);
g.drawImage(duke, xPos, yPos, this);
}

public void mousePressed(MouseEvent e) {
xPos = e.getX();
yPos = e.getY();
repaint();
}

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