### Add Button Icon using Code

Adding an icon via code can be done by either using the library CSSUtils or via JavaObject which a Button is assigned to.
The image must be located in the files folder (dirassets) and added to the B4J IDE Files Manager.
B4J Code and CSSUtils Library (Gravity Full)
Select CSSUtils in the B4J IDE Library Manager.
Set button btnAdd background image "list-add.png".
The icon file "list-add.png" is located in the project files folder (DirAssets) and added to the B4J IDE Files Manager.
Dim btnAdd As Button
CSSUtils.SetBackgroundImage(btnAdd, File.DirAssets, "list-add.png")
The Gravity of the button is full.
B4J Code and CSSUtils Library (Gravity Center)
Select CSSUtils in the B4J IDE Library Manager.
' Add an icon, located in the files folder (dirassets ) to a button. The icon gravity is center.
' Example: AddButtonIcon(btnAdd, "list-add.png")
`Sub AddButtonIcon(btn As Button, icon As String)
CSSUtils.SetStyleProperty(btn, "-fx-background-color", "transparent")
CSSUtils.SetStyleProperty(btn, "-fx-background-position","center")
CSSUtils.SetStyleProperty(btn, "-fx-background-repeat", "no-repeat")
Dim iconpath As String = File.GetUri(File.DirAssets, icon)
CSSUtils.SetStyleProperty(btn, "-fx-background-image", $"url('${iconpath}');"$)
End Sub`
B4J Code and Library JavaObject
The API method setGraphic is called.
References:
https://docs.oracle.com/javase/8/javafx/api/javafx/scene/control/Button.html
https://docs.oracle.com/javafx/2/api/javafx/scene/control/Button.html
Example
`Sub AppStart (Form1 As Form, Args() As String)
...
'Define the button and add to the rootpane of the mainform
Dim btn As Button
btn.Initialize("btn")
btn.Tag = "This is my ImageButton"
MainForm.RootPane.AddNode(btn, 20,20,50, 50)
'Create the imageview and add to the button
Dim iv As ImageView
iv.Initialize("")
'Ensure the image myimage.png is added to the files tab and stored in the files folder
iv.SetImage(fx.LoadImage(File.DirAssets, "myimage.png"))
ButtonSetGraphic(btn, iv)
End Sub`
'Add the icon using API call
`Sub ButtonSetGraphic(btn As Button, Graphic As Node)
Dim jo As JavaObject = btn
jo.RunMethod("setGraphic", Array(Graphic))
End Sub`
`Sub btn_Action
Dim b As Button = Sender
Log("Clicked Button..." & b.Tag)
End Sub`

Changed: 2018-03-28 10:04, Category: Buttons, File: T6C167M1225.htm, ID: 1225