Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 574
rtheunissen Avatar asked Jul 05 '11 01:07

rtheunissen


1 Answers

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.

like image 141
Paŭlo Ebermann Avatar answered Sep 28 '22 06:09

Paŭlo Ebermann