从面板绘制的复合树中检索单击的组件

时间:2012-11-07 21:23:42

标签: java swing jpanel mouseevent paintcomponent

我有一个复合树。我通过覆盖JPanel将此树绘制为Graphics宽度paintComponent(Graphics gr)对象。我的问题是:如何访问点击哪个组件?

我只想出了琐碎和糟糕的解决方案,所以这就是我转向你的原因。提前谢谢!

1 个答案:

答案 0 :(得分:2)

您需要存储的形状。 当您收到鼠标单击事件时:

public void mouseClicked(MouseEvent e) {

你将拥有来自

的x和y
    e.getPoint().getX()
    e.getPoint().getY()

然后,您可以遍历形状,并查看Shape是否包含上述点。来自形状的Javadoc:

/**
 * Tests if the specified coordinates are inside the boundary of the
 * <code>Shape</code>, as described by the
 * <a href="{@docRoot}/java/awt/Shape.html#def_insideness">
 * definition of insideness</a>.
 * @param x the specified X coordinate to be tested
 * @param y the specified Y coordinate to be tested
 * @return <code>true</code> if the specified coordinates are inside
 *         the <code>Shape</code> boundary; <code>false</code>
 *         otherwise.
 * @since 1.2
 */
public boolean contains(double x, double y);