working with images

hi,

i've placed an image in the frame and I've written mouse movement. it is ok for single image. but if i use multiple images and i need to select particular image and move it to a position. i don wan to work with cursor. i want to work with individual component. please review my code below to get clear idea

import java.awt.*;

import javax.swing.*;

import java.awt.Color;

import java.awt.Graphics;

import java.awt.event.MouseEvent;

import javax.swing.JFrame;

import javax.swing.JPanel;

import javax.swing.event.MouseInputAdapter;

publicclass MoveImageextends JFrame

{

privatefinalstaticint SQUARE_EDGE_LENGTH = 40;

private Image image;

String img1="icons/Capacitance.gif";

private JPanel panel;

privateint xPos;

privateint yPos;

public MoveImage(String s)

{

super(s);

setSize(new Dimension(1022, 725));

this.setDefaultCloseOperation(javax.swing.JFrame.EXIT_ON_CLOSE);

xPos = 50;

yPos = 50;

this.setVisible(true);

Toolkit toolkit = Toolkit.getDefaultToolkit();

image = toolkit.getImage(img1);

MediaTracker mediaTracker =new MediaTracker(this);

mediaTracker.addImage(image, 0);

try

{

mediaTracker.waitForID(0);

}catch (InterruptedException ie){System.err.println(ie);}

panel =new JPanel()

{

publicvoid paint(Graphics g)

{

super.paintComponent(g);

g.setColor(Color.RED);

g.drawImage(image, xPos-(SQUARE_EDGE_LENGTH/2), yPos-(SQUARE_EDGE_LENGTH/2),null);

//g.drawImage(image, xPos-(SQUARE_EDGE_LENGTH/2), yPos-(SQUARE_EDGE_LENGTH/2), null);

}

};

MouseInputAdapter mia =new MouseInputAdapter()

{

publicvoid mousePressed(MouseEvent e)

{

xPos = e.getX();

yPos = e.getY();

panel.repaint();

}

publicvoid mouseDragged(MouseEvent e)

{

xPos = e.getX();

yPos = e.getY();

panel.repaint();

}

};

add(panel);

panel.addMouseListener(mia);

panel.addMouseMotionListener(mia);

}

publicstaticvoid main(String args[])

{

new MoveImage("Move my Image");

}

}

~radha

[4264 byte] By [radhadevi19840320a] at [2007-11-26 18:53:28]
# 1

Add your image to a JLabel and add the label to the panel.

Then you add a MouseListener and MouseMotionListener to the panel.

On a mousePressed event you use the findComponentAt(..) method to determine which label you clicked on.

On a mouseDragged event you move the label by changing its location.

camickra at 2007-7-9 6:27:29 > top of Java-index,Desktop,Core GUI APIs...