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

1

8

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:

enter image description here

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?

Bimonthly answered 5/7, 2011 at 1:16 Comment(1)
Hm, how about use one or more concrete classes derived from the Shape interface? This has a contains method that would come in handy. Rotation would be easy per use of AffineTransform.Alves
G
5

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.

Galore answered 5/7, 2011 at 2:11 Comment(2)
Worked perfectly. The solution is to use AffineTransform's createTransformedShape and then check if that shape contains the Point of a mouse-click. Thanks.Bimonthly
@paranoid-android: You should accept this answer by clicking the tick at the left of this answer.Anastomosis

© 2022 - 2024 — McMap. All rights reserved.