A class for moving objects
Hi
I have this code, but thats not exactly what I need.
As I'm a beginner in Java2D I'll ned some help, please.
The code:
publicclass ArrastaImagemextends JPanel{
private BufferedImage image;
Rectangle r;
// construtor recebe uma imagem
public ArrastaImagem(BufferedImage image){
super();// construtor de JPanel
this.image = image;// this -> aponta para valor recebido (a vari醰el da classe assume o valor da vari醰el recebida)
r =new Rectangle(5, 5, image.getWidth(), image.getHeight());// ret鈔gulo com tamnho da imagem
}
protectedvoid paintComponent(Graphics g){
super.paintComponent(g);
Graphics2D g2d = (Graphics2D)g;
g2d.drawImage(image, r.x, r.y,this);
}
publicvoid setRect(int x,int y){
r.x = x;
r.y = y;
repaint();
}
publicstaticvoid main(String[] args)throws IOException{
// carrega imagem
File file =new File("C:/foto.png");
BufferedImage image = ImageIO.read(file);
ArrastaImagem ai =new ArrastaImagem(image);
ControlaArrasto handler =new ControlaArrasto(ai);
ai.addMouseListener(handler);
ai.addMouseMotionListener(handler);
JFrame f =new JFrame("Arrastando uma imagem na tela");
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.setContentPane(ai);
f.setSize(400,400);
f.setLocation(200,200);
f.setVisible(true);
}
}
class ControlaArrastoextends MouseInputAdapter{
ArrastaImagem di;// fornece os dados e os m閠odos p鷅licos da classe
Point offset;
boolean dragging;
public ControlaArrasto(ArrastaImagem di){
this.di = di;
offset =new Point();
dragging =false;
}
publicvoid mousePressed(MouseEvent e){
Point p = e.getPoint();// captura a posi玢o onde o mouse foi clicado
if(di.r.contains(p)){// verifica se retangulo cont閙 estes pontos
offset.x = p.x - di.r.x;// diferen鏰 de posi玢o entre o clique e x0 do ret鈔uglo - altera x de offset (Point)
offset.y = p.y - di.r.y;// diferen鏰 de posi玢o entre o clique e y0 do ret鈔uglo - altera y de offset (Point)
dragging =true;
}
}
publicvoid mouseReleased(MouseEvent e){
dragging =false;
}
publicvoid mouseDragged(MouseEvent e){
if(dragging){
// sem diferen鏰 entre o clique e x,y inicial do ret鈔gulo
//int x = e.getX();
//int y = e.getY();
// Posiciona ret鈔gulo entre a diferen鏰 do click e x,y do ret鈔gulo
int x = e.getX() - offset.x;
int y = e.getY() - offset.y;
di.setRect(x, y);// m閠odo de ArrastaImagem
}
}
}
Yeah, I know...some names are in portuguese!
Well, there are a few things I need help for:
1. How to create an "optimal and general" class for drag (Arrasta) an object/image on a component
2. How to add several objects/imagens along the program ? Must use a Collection? How to and which one?
3. After have some images, like 5 for example. How to set the focus when I click over it (could become colorfull, while the others are B&W) and how to bring it to front if it happends to be behind some other?
Thaks a lot...It's a little tricky to me to do on my own!
joddy
[5839 byte] By [
schafera] at [2007-11-26 16:38:05]

# 1
Must use a Collection? How to and which one?
No, you can use arrays. If you do want to use a Collection I recommend ArrayList.
Images found at the bottom of [url=http://java.sun.com/docs/books/tutorial/uiswing/components/examples/index.html]Using Swing Components: Examples[/url].
import java.awt.*;
import java.awt.event.*;
import java.awt.image.BufferedImage;
import java.io.*;
import javax.imageio.ImageIO;
import javax.swing.*;
import javax.swing.event.MouseInputAdapter;
public class AI extends JPanel implements ActionListener {
private BufferedImage[] images;
Rectangle[] rects;
int[] orderIndices;
int selectedRect = -1;
public AI(BufferedImage[] images) {
super();
this.images = images;
rects = new Rectangle[1];
rects[0] = new Rectangle(5, 5, images[0].getWidth(),
images[0].getHeight());
orderIndices = new int[1];
}
public void actionPerformed(ActionEvent e) {
int count = rects.length % images.length;
Rectangle r = new Rectangle(images[count].getWidth(),
images[count].getHeight());
r.x = (getWidth() - r.width)/2;
r.y = (getHeight() - r.height)/2;
addRect(r);
repaint();
}
private void addRect(Rectangle r) {
Rectangle[] temp = new Rectangle[rects.length+1];
System.arraycopy(rects, 0, temp, 0, rects.length);
temp[rects.length] = r;
rects = temp;
int[] tempIndices = new int[orderIndices.length+1];
System.arraycopy(orderIndices, 0, tempIndices, 0, orderIndices.length);
tempIndices[orderIndices.length] = orderIndices.length;
orderIndices = tempIndices;
}
protected void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2d = (Graphics2D)g;
for(int j = 0; j < orderIndices.length; j++) {
int k = orderIndices[j];
if(k == selectedRect) {
g2d.setPaint(Color.red);
Rectangle r = (Rectangle)rects[k].clone();
r.grow(4,4);
g2d.fill(r);
}
int nextImage = k % images.length;
g2d.drawImage(images[nextImage], rects[k].x, rects[k].y, this);
}
}
public void setRect(int x, int y) {
rects[selectedRect].setLocation(x, y);
repaint();
}
public void setSelection(int orderIndex) {
selectedRect = orderIndex;
//System.out.printf("selectedRect = %d%n", selectedRect);
if(orderIndex != -1) {
selectedRect = orderIndices[orderIndex];
resetIndices(orderIndex);
}
repaint();
}
private void resetIndices(int selectedIndex) {
// Save index of image at selectedIndex in indices array.
int topImageIndex = orderIndices[selectedIndex];
// Slide all later (than selectedIndex) values down one place.
//System.out.printf("before = %s",
//java.util.Arrays.toString(orderIndices));
for(int j = selectedIndex; j < orderIndices.length-1; j++)
orderIndices[j] = orderIndices[j+1];
// Put topImageIndex in last place (top of vertical).
orderIndices[orderIndices.length-1] = topImageIndex;
//System.out.printf("after = %s%n",
//java.util.Arrays.toString(orderIndices));
}
private JPanel getLastPanel() {
JButton button = new JButton("add image");
button.addActionListener(this);
JPanel panel = new JPanel();
panel.add(button);
return panel;
}
public static void main(String[] args) throws IOException {
String[] ids = { "-c", "--g--", "h-", "-t", "-cgh-", "-cght" };
String prefix = "images/geek";
String ext = ".gif";
BufferedImage[] images = new BufferedImage[ids.length];
for(int j = 0; j < images.length; j++) {
File file = new File(prefix + ids[j] + ext);
images[j] = ImageIO.read(file);
}
AI ai = new AI(images);
ControlaArrasto handler = new ControlaArrasto(ai);
ai.addMouseListener(handler);
ai.addMouseMotionListener(handler);
JFrame f = new JFrame("Arrastando uma imagem na tela");
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.getContentPane().add(ai);
f.getContentPane().add(ai.getLastPanel(), "Last");
f.setSize(400,400);
f.setLocation(200,200);
f.setVisible(true);
}
}
class ControlaArrasto extends MouseInputAdapter {
AI component;
Point offset;
boolean dragging;
public ControlaArrasto(AI di) {
component = di;
offset = new Point();
dragging = false;
}
public void mousePressed(MouseEvent e) {
Point p = e.getPoint();
Rectangle[] rects = component.rects;
int[] indices = component.orderIndices;
for(int j = indices.length-1; j >= 0; j--) {
Rectangle r = rects[indices[j]];
if(r.contains(p)) {
offset.x = p.x - r.x;
offset.y = p.y - r.y;
dragging = true;
component.setSelection(j);
break;
}
}
}
public void mouseReleased(MouseEvent e) {
dragging = false;
component.setSelection(-1);
}
public void mouseDragged(MouseEvent e) {
if(dragging) {
int x = e.getX() - offset.x;
int y = e.getY() - offset.y;
component.setRect(x, y);
}
}
}