B4J Code Snippet GetScreenPosition

Discussion in 'B4J Code Snippets' started by jmon, Jan 29, 2015.

  1. jmon

    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.

    Code:
    '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 NodeAs 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: Aug 20, 2016
    xulihang, JakeBullet70 and Erel like this.
  2. rwblinn

    rwblinn Well-Known Member Licensed User

    Hi,

    thanks a lot - good.
    Small hint on defining the map m is to use CreateMap instead:
    Code:
    Dim m As Map = CreateMap("x":0"y":0)
     
    Erel and jmon like this.
  3. jmon

    jmon Well-Known Member Licensed User

    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.
     
  4. jmon

    jmon Well-Known Member Licensed User

    I updated the function in first post. The previous one wasn't returning correct results if called several times in a row in some cases.
     
    JakeBullet70 and inakigarm like this.
Loading...
  1. This site uses cookies to help personalise content, tailor your experience and to keep you logged in if you register.
    By continuing to use this site, you are consenting to our use of cookies.
    Dismiss Notice