B4J Question How to add an icon to a button via code

ivan.tellez

Active Member
Licensed User
Longtime User
Its is possible to add an Icon from the Files folder to a button created in code?

This works with files outside the compiled jar:

B4X:
  Dim tButton As Button
  tButton.Initialize("RibbonButton")
  tButton.Style = "-fx-background-position: center top;  -fx-background-repeat: no-repeat;  -fx-background-image: url('file:///z:/save.png');"
  tButton.Alignment = "BOTTOM_CENTER"
  tSection.AddNode(tButton, 0, 0, 70, 70)

But, how to use images added to the files tab?

Thanks
 

Roycefer

Well-Known Member
Licensed User
Longtime User
Files added to the Files tab will be found in File.DirAssets. You can copy them to a temporary folder and then load them from there.
 
Upvote 0

jmon

Well-Known Member
Licensed User
Longtime User
Your code works just load the path of the image this way:
B4X:
$"-fx-background-image: ${File.GetUri(File.DirAssets, "save.png")};"$

Otherwise, this method is my prefered one:

(Requires JavaObject):
B4X:
Public Sub NodeSetImage(n As Node, ImageDir As String, ImageFileName As String, Width As Int, Height As Int, ContentDisplay As String)
    'Check that path and filename are valid:
    If ImageDir = "" Or ImageFileName = "" Then Return
    'Set the button image:
    Dim iv As ImageView
    Dim nJo As JavaObject = n
    iv = nJo.RunMethod("getGraphic", Null)
    If iv.IsInitialized Then
        iv.SetImage(fx.LoadImageSample(ImageDir, ImageFileName, iv.Width, iv.Height))
    Else
        iv.Initialize("")
        If Width > -1 Then
            iv.Width = Width
        End If
        If Height > -1 Then
            iv.Height = Height
        End If
        iv.SetImage(fx.LoadImageSample(ImageDir, ImageFileName, iv.Width, iv.Height))
        nJo.RunMethod("setGraphic", Array(iv))
        Dim cd As JavaObject
        cd.InitializeStatic("javafx.scene.control.ContentDisplay")
        nJo.RunMethod("setContentDisplay", Array(cd.RunMethod("valueOf", Array(ContentDisplay))))
    End If
End Sub

Where ContentDisplay is any of the string values here : https://docs.oracle.com/javase/8/javafx/api/javafx/scene/control/ContentDisplay.html
i.e : "LEFT"

Works for both if the image was already set in the designer, or buttons or other nodes without images set.

Works for buttons, labels, titledPanes.

jmon.
 
Last edited:
Upvote 0
Top