Java: getting the absolute position of the mouse in a JPanel given the coordinate the user clicked on
For example, suppose I have a drawing in a JPanel subclass with JScrollPanes, and I want to capture the points the user clicks on. Suppose, for example, the drawing area i开发者_JAVA技巧nside the JPanel goes from 0 to 10000, while the screen size isn't known a priori. Given the mouse coordinates in the click event thing, is it possible to determine where in the 0 - 10000 range it actually is? For example, the coordinate on the screen would be (300, 500) according to the event but the actual position in the canvas could be (5890, 3200).
Mouse co-ordinates when delivered to a component are given relative to the the component, so your JPanel you would see 5890,3200 if that were the visible part the mouse was clicked on. If you have to translate from screen co-ordinates, you can use JViewport to find the co-ordinates of the view that are presently visible in the viewport, via JViewport.getViewRect(). You get the viewport from the JScrollPane via JScrollPane.getViewport().
精彩评论