How to generate events from graphics generated by Java2D

落爺英雄遲暮 提交于 2019-12-31 02:22:27

问题


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.


回答1:


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.




回答2:


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:

  1. Store the Ellipse2D objects from which the ellipses were drawn from in a List.
  2. Register a MouseListener on the Swing component where the user is to click on.
  3. From the MouseEvents generated from the mouse clicks, determine the location at which the mouse was clicked (using MouseEvent.getPoint), and check if the mouse click occurred in any of the Ellipse2Ds contained in the aforementioned List, using the Ellipse2D.contains method.



回答3:


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)



来源:https://stackoverflow.com/questions/2020607/how-to-generate-events-from-graphics-generated-by-java2d

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!