例如, 我把一个小地图图像加载在canvas画布上,我鼠标点击小地图图像,怎么获取鼠标点击的地点(比如我点击的是火车站),java怎么知道我点的就是火车站,而不是其他地点的

解决方案 »

  1.   

    思路,给画布加入鼠标监听器addMouseListener, addMouseMotionListener, 监听方法里event.getPoint()返回鼠标位置
    你的火车站,最起码要保留x ,y width height 4个数据,可以建成Rectangle 或其它形状(Shape的子类)
    Rectangle.contains(point) 返回true 则鼠标点到了
    还有一些实用工具:
    SwingUtilities.converPointFromScreen(point,aComponent) //把屏幕坐标point转为以一个组件aComponent
    的x,y作原点的相对坐标
    aComponent.getLocationOnScreen() 转成屏幕坐标, 这两方法很实用