Search code examples
javagraphicsmouse-cursor

How to see if mouse cursor is hovering over a java graphics2D translated object


I have a rectangle, and have translated it through scale and rotation to a new position on the screen. What I want is to be able to detect when the mouse cursor is hovering over this object on the screen. And not its original non-translated form. I have provided runnable code to display my problem below

import java.awt.*;
import java.awt.event.*;
import java.awt.geom.Path2D;
import java.util.*;
import javax.swing.*;
import javax.swing.Timer;

public class Main extends JPanel {

    static int WIDTH;
    static int HEIGHT;

    public Main(){
    }

    public void paintComponent(Graphics g){
        super.paintComponent(g);
        Graphics2D g2d = (Graphics2D) g;
        g2d.setColor(Color.RED);
        g2d.fillRect(WIDTH/2, HEIGHT/2, 100, 100);
        g2d.rotate(Math.toRadians(45),WIDTH/2,HEIGHT/2);
        g2d.scale(0.5, 0.5);
        g2d.setColor(Color.BLUE);
        g2d.fillRect(WIDTH/2, HEIGHT/2, 100, 100);

    }
    public static void main(String[] args){
        Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
        WIDTH = (int) screenSize.getWidth();
        HEIGHT = (int) screenSize.getHeight();
        Main main = new Main();
        JFrame frame = new JFrame();
        frame.setTitle("360 ATTACK");
        frame.setSize(WIDTH, HEIGHT);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.add(main);
        frame.setVisible(true);
    }
}

So to re-iterate, I want to know when the mouse cursor is hovering over the blue shape. Not the red shape.

Thanks


Solution

  • You can use Area and Area.contains(x,y);

    Rectangle r = ...;
    Area a = new Area(r);
    a.transform(AffineTransform.rotate(Math.PI/2));
    if (a.contains(event.getX(), event.getY()) {
      ...
    }
    

    I recommend keeping track of the Area in a instance variable so that you can access it in the MouseMotionListener

    Also see this Area package - everything that starts with 'Area' here : https://sourceforge.net/p/tus/code/HEAD/tree/tjacobs/ui/shape