How do I make a rectangle move in an image?

Posted by alicedimarco on Stack Overflow See other posts from Stack Overflow or by alicedimarco
Published on 2011-11-20T14:34:11Z Indexed on 2011/11/20 17:50 UTC
Read the original article Hit count: 203

Basically I have an image loaded, and when I click a portion of the image, a rectangle (with no fill) shows up. If I click another part of the image again, that rectangle will show up once more. With each click, the same rectangle should appear.

So far I have this code, now I don't know how to make the image appear. My image from my file directory. I have already made the code to get the image from my file directory.

import java.awt.Color;
import java.awt.Graphics;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;

import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JPanel;

public class MP2 extends JPanel implements MouseListener{

    JFrame frame;
    JPanel panel;

    int x = 0;
    int y = 0;
    String input;

    public MP2(){

    }

    public static void main(String[] args){
        JFrame frame = new JFrame();
        MP2 panel = new MP2();
        panel.addMouseListener(panel);
        frame.add(panel);
        frame.setSize(200,200);
        frame.setVisible(true);

    }

    public void mouseClicked(MouseEvent event) {
        // TODO Auto-generated method stub

        this.x = event.getX();
        this.y = event.getY();
        this.repaint();
        input = JOptionPane.showInputDialog("Something pops out");
        System.out.println(input);

    }

    public void mouseEntered(MouseEvent arg0) {
        // TODO Auto-generated method stub
    }

    public void mouseExited(MouseEvent arg0) {
        // TODO Auto-generated method stub

    }

    public void mousePressed(MouseEvent arg0) {
        // TODO Auto-generated method stub

    }

    public void mouseReleased(MouseEvent arg0) {
        // TODO Auto-generated method stub

    }

    public void paintComponent(Graphics g){
        super.paintComponent(g);

        // this.setBackground(Color.white); *Sets the bg color of the panel

        g.setColor(new Color(255,0,0));
        g.drawRect(x, y, 100, 100);
    }
}

© Stack Overflow or respective owner

Related posts about java

Related posts about swing