How can you detect a mouse-click event on an Image object in Java?

*爱你&永不变心* 提交于 2019-12-01 15:18:29

问题


Implementing "Kings' Corners" (glorified multiplayer Solitaire) in Java.

I'm trying to allow a player to drag a card (image) from their hand to somewhere else on the table. The problem is that the player's hand is "fanned" so the images of the cards are rotated and they overlap.

Here is an example of a hand:

I've considered making each card a JPanel, but the issue then is that I'd have to paint the card rotated inside its rectangular JPanel, as they themselves can't be rotated. Ideally I'd like to avoid mouse-x,y formulas to determine which card is being chosen.

Using an event-driven approach, how can I determine which card is chosen from the hand?


回答1:


AWT (and Swing) components are normally rectangular (aligned to the axes).

But this does not have to be the case - while the real bounds must be rectangular, the actual area which a component uses can be smaller. Component supports a contains(Point) method, which will get called by the event dispatch mechanism whenever the question arises to which component a point belongs - for example, for mouse clicks. (Overlapping of different components will be handled by the z-order inside the parent container.)

You can implement this method based on the Shape.contains() method, using a affine transformed rectangle as your shape. Each of your rotated components would know its own shape (or generate it on the fly from its AffineTransform, the same one which would also be used for painting itself).

Have a custom LayoutManager which arranges your cards, too. (Don't use CardLayout, despite the name.)

I'm not sure I would follow the way of having separate components for each card, but you certainly need some objects which represent the rotated rectangles.



来源:https://stackoverflow.com/questions/6577227/how-can-you-detect-a-mouse-click-event-on-an-image-object-in-java

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