• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 246
  • Last Modified:

Images in canvas

I have 2 img and I would use them to create my slider. I know I have to use canvas. One img suppose to goes strieght back and force meantime other is not moving.Please show some example.
1 Solution
Here is an example of a component that draws an image and allows dragging it around with your mouse. From what I understand you want something similar but that moves just around the x OR y axis... should be easy to modify:

public class MyComponent extends Canvas{

  private Image dbImage; // Image for double buffering, to avoid flickering.
  private Image myImage;
  private int imageX=0, imageY=0; // The location of our image;

  private int lastDragX, lastDragY;

  public MyComponent(Image image){
     myImage = image;

  public void update(Graphics g){
     Graphics dbGraphics = getDBGraphics();

  public void paint(Graphics g){

  public boolean mouseDown(Event e, int x, int y){
     lastDragX = x;
     lastDragY = y;
     return false;

  public boolean mouseDrag(Event e, int x, int y){
     imageX += x-lastDragX;
     imageY += y-lastDragY;
     lastDragX = x;
     lastDragY = y;
     return false;


  private final Graphics getDBGraphics(){
     if ((dbImage == null) || ((dbImage.getWidth(null)!=(int)getIBounds().getWidth())||
       dbImage = createImage((int)Math.max(getIBounds().getWidth(),1),
   // Using Math.max is needed because createImage only takes positive
   // values, which seems strange to me, since components can even
   // have negative size.
     return dbImage.getGraphics();


Hope this helps, Sasha.

R u using Swing?
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

Join & Write a Comment

Featured Post

Free Tool: Site Down Detector

Helpful to verify reports of your own downtime, or to double check a downed website you are trying to access.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

Tackle projects and never again get stuck behind a technical roadblock.
Join Now