alicedimarco
alicedimarco

Reputation: 325

How to make a shape appear on top of an image when mouse is clicked?

I'm aiming for the appearance of a rectangle when the mouse is clicked. Here's a snippet of my current code:

    try{
            image = ImageIO.read(file);
            g.setColor(new Color(255,0,0));
            g.drawRect(x, y, 100, 100);
            }

    icon = new ImageIcon(image);
    label = new JLabel(icon);
    label.addMouseListener(this);

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

            if(event.getSource() == label){

                x = event.getX();
                y = event.getY();

                repaint();

                input = JOptionPane.showInputDialog("Something:");
                System.out.println(input);
            }
        }

Upvotes: 2

Views: 739

Answers (1)

GETah
GETah

Reputation: 21449

You can extend a JPanel to do exactly what you want:

class MyPanel extends JPanel{
    //....
    private java.awt.Rectangle rectangle = null;
    private Image imageToDraw;
    private Point imageLocation;
    public setImageToDraw(Image toDraw,Point p){
      imageToDraw=toDraw;
      imageLocation = p;
    }
    public void setRectangle(java.awt.Rectangle rectangle overlayRect){
       rectangle = overlayRect;
    }
    // Override paintComponent to draw image and rectangle
    @Override
    public void paintComponent(Graphics g) {
      g.drawImage(imageToDraw,imageLocation.getX(),imageLocation.getY(),this);
      if(rectangle != null) {
         // Draw your rectangle here...
      }
    }
}

In your mouse listener, do the following:

// Declare a field of type MyPanel
private MyPanel drawingPanel = new MyPanel
// ... Initialization stuff...
drawingPanel.setImageToDraw(toDraw,p);
public void mouseReleased(MouseEvent event) {
        // TODO Auto-generated method stub
        if(event.getSource() == label){
           // Compute rectangle boundaries
           drawingPanel.setRectangle(overlayRect);
        }
        drawingPanel.repaint();
}

Basically, a MyPanel object will always have the image to draw set. This way the image is drawn on the panel all the time. When you want an overlay rectangle, all what you have to do is to set the MyPanel.rectangle field and refresh your MyPanel instance. This will redraw the image first and then draw the overlay rectangle on top of the image.

Upvotes: 3

Related Questions