如何从 Java2D 生成的图形生成事件
我在 java.awt.geom.Ellipse2D 的帮助下制作了一个椭圆
现在,我希望每当用户单击该椭圆时,都会生成一个事件,以便我可以监听该事件并根据生成的椭圆执行后续任务那个事件。
I have made an Ellipse with the help of java.awt.geom.Ellipse2D
Now, I want that whenever user clicks on that ellipse, an event is generated so that I can listen to that event and peform subsequent tasks based on the ellipse which generated that event.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
下面是一个简单的对象绘制程序示例,演示了单击、拖动和多项选择。还可以考虑 JGraph,它是一个更高级的图形可视化库。
Here is a simple example of an object drawing program that demonstrates click, drag and multiple selection. Also consider JGraph, which is a much more advanced library for graph visualization.
我假设这是一个询问如何监听鼠标点击的问题,这些鼠标点击是使用
Graphics2D.draw
。简单的答案是,无法从表面上绘制的图形生成鼠标事件。
但是,这里有一种替代方法:
List
中从中绘制椭圆。MouseListener
用户要单击的 Swing 组件上。MouseEvent
由鼠标点击生成,确定鼠标被点击的位置(使用MouseEvent.getPoint
),并检查鼠标点击是否发生在任何Ellipse2D
包含在上述List
中,使用Ellipse2D.contains
方法。I'm going to assume this is a question asking a way to listen to mouse clicks which are made on an ellipse drawn on some Swing component using
Graphics2D.draw
.The simple answer is, there is no way to generate mouse events from graphics drawn on a surface.
However, here's an alternative approach:
Ellipse2D
objects from which the ellipses were drawn from in aList
.MouseListener
on the Swing component where the user is to click on.MouseEvent
s generated from the mouse clicks, determine the location at which the mouse was clicked (usingMouseEvent.getPoint
), and check if the mouse click occurred in any of theEllipse2D
s contained in the aforementionedList
, using theEllipse2D.contains
method.我认为如果没有大量手工编码的东西(让画布或其他东西,监听鼠标事件,并计算自己是否单击了椭圆),这是不可能的。
如果你想做更多类似的事情,请考虑场景图。这样,椭圆本身就是一个对象,您可以注册事件侦听器。
编辑作为对评论的回应:
场景图: https://scenegraph.dev.java.net/
谷歌获取更多资源:scenegraph java
是的。 Scenegraph 是 JavaFX 的一部分,但可以很好地与纯 Java(无 FX)配合使用
I don't think this is possible without lots of handcoded stuff (letting the canvas or whatever, listen to mouse events, and calculating yourself if the ellipse was clicked on).
If you want to do more like that consider scenegraph. With that the ellipse would be an object in its own right and you can register event listeners.
Edit as response to comment:
Scenegraph: https://scenegraph.dev.java.net/
google for more resources: scenegraph java
And yes. Scenegraph ist part of the JavaFX stuff, but works nicely with pure Java (no FX)