B4J Code Snippet GetScreenPosition

Similar threads

B4J Code Snippet B4XDialog - Add keyboard handling
B4J Code Snippet Metro Style with JMetro
B4J Code Snippet Cool zooming effect
B4J Code Snippet Measure Multiline Text Height
B4A Code Snippet [B4X] Use WebView to show large images

jmon

Well-Known Member
Licensed User
Hi,

This snippet gives you the screen position of a node in your application. Useful when you have a pop-up that needs to be aligned to a control, like a tooltip for example.

B4X:
'Returns a map containing the x and y screen position values
'for the given node. If coordinates are not found, then return 0
'
'Example:
'Dim ScreenPos As Map = GetScreenPosition(MyNode)
'ScreenPos.Get("x")
'ScreenPos.Get("y")
Private Sub GetScreenPosition(n As Node) As Map
    Dim m As Map = CreateMap("x": 0, "y": 0)
    Dim x = 0, y = 0 As Double
    Dim joNode = n, joScene, joStage As JavaObject
  
    'Get the scene position:
    joScene = joNode.RunMethod("getScene",Null)
    If joScene.IsInitialized = False Then Return m
    x = x + joScene.RunMethod("getX", Null)
    y = y + joScene.RunMethod("getY", Null)

    'Get the stage position:
    joStage = joScene.RunMethod("getWindow", Null)
    If joStage.IsInitialized = False Then Return m
    x = x + joStage.RunMethod("getX", Null)
    y = y + joStage.RunMethod("getY", Null)
  
    'Get the node position in the scene:
    Do While True
        y = y + joNode.RunMethod("getLayoutY", Null)
        x = x + joNode.RunMethod("getLayoutX", Null)
        joNode = joNode.RunMethod("getParent", Null)
        If joNode.IsInitialized = False Then Exit
    Loop

    m.Put("x", x)
    m.Put("y", y)
    Return m
End Sub
Enjoy!
 
Last edited:

rwblinn

Well-Known Member
Licensed User
Hi,

thanks a lot - good.
Small hint on defining the map m is to use CreateMap instead:
B4X:
Dim m As Map = CreateMap("x":0, "y":0)
 

jmon

Well-Known Member
Licensed User
Hi,

thanks a lot - good.
Small hint on defining the map m is to use CreateMap instead:
B4X:
Dim m As Map = CreateMap("x":0, "y":0)
Thanks,

I totally forgot this function! I think I have seen that somewhere, but didn't pay attention to it. Thanks for the reminder!

By the way, I forgot to mention that this snippet works with child windows too, and child of child of child ...

Thank you.
 

jmon

Well-Known Member
Licensed User
Top