【问题标题】:How to see if mouse cursor is hovering over a java graphics2D translated object如何查看鼠标光标是否悬停在 java graphics2D 翻译对象上
【发布时间】:2021-12-31 01:58:19
【问题描述】:

我有一个矩形,并通过缩放和旋转将其平移到屏幕上的新位置。我想要的是能够检测鼠标光标何时悬停在屏幕上的该对象上。而不是其原始的非翻译形式。我提供了可运行的代码来在下面显示我的问题

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);
    }
}

所以要重新迭代,我想知道鼠标光标何时悬停在蓝色形状上。不是红色的形状。

谢谢

【问题讨论】:

    标签: java graphics mouse-cursor


    【解决方案1】:

    你可以使用Area和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()) {
      ...
    }
    

    我建议在实例变量中跟踪区域,以便您可以在 MouseMotionListener 中访问它

    另请参阅此区域包 - 此处以“区域”开头的所有内容:https://sourceforge.net/p/tus/code/HEAD/tree/tjacobs/ui/shape

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-08-14
      • 1970-01-01
      • 1970-01-01
      • 2021-12-17
      • 2014-01-31
      • 2018-11-12
      • 2020-11-13
      • 1970-01-01
      相关资源
      最近更新 更多