如何在Java中的Image对象上检测鼠标点击事件? [英] How can you detect a mouse-click event on an Image object in Java?

查看:147
本文介绍了如何在Java中的Image对象上检测鼠标点击事件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述



我试图允许玩家拖动一个玩家卡(图)从他们的手到桌子上的其他地方。问题是玩家的手是扇形,所以卡的图像被旋转并且它们重叠。



这是一个例子:





我已经考虑将每张卡片设为 JPanel ,但问题是我必须在其矩形 JPanel ,因为它们本身不能旋转。理想情况下,我想避免使用鼠标x,y公式来确定选择哪张卡。



使用事件驱动的方法,如何确定哪个卡是从手中选择?

解决方案

AWT(和Swing)组件通常是矩形(与轴对齐)。



但这不一定是这种情况 - 而实际的边界必须是矩形,组件使用的实际面积可以更小。组件支持一个 contains(Point)方法,只要问题出现在某个点所属的组件 - 例如鼠标点击时,它将被事件调度机制调用。 (不同组件的重叠将由父容器中的z顺序处理。)



您可以基于 Shape实现此方法。 contains()方法,使用仿射变换矩形作为形状。每个旋转的组件都会知道自己的形状(或者从它的AffineTransform飞行中生成它的形状,也可以用于绘画本身)。



有一个自定义的LayoutManager也可以安排你的卡片。 (不要使用CardLayout,尽管名字。)



我不知道我会按照每张卡分开的组件的方式,但你一定需要一些表示旋转矩形的对象。


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?

解决方案

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.

这篇关于如何在Java中的Image对象上检测鼠标点击事件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆