Share My Creation Creating javafx buttons with images

Hi, 'b4jers'
B4j can easily import and encompass the javafx controls and deals with them as native controls. As a demo of this power of b4j
I present this outcome of a small app that took a considerable deal of research, trials and errors, and code organization..
It displays three buttons imported from javafx, two of them are with images.. their events were brought to b4j and used to show
an open file dialog and a save file dialog also imported from javafx by the same way of getting the buttons.
Have a nice day..
 

jkhazraji

Active Member
Licensed User
Longtime User
Actually I was thinking about a button image / button icon for my b4j app some time ago. This should be handy.
B4X:
 Dim btn as JavaObject
'
'
'

Dim imgPath As String =File.Combine(File.DirApp,"home32.png")
btn=(Me).As(JavaObject).RunMethod("createButtonWithImage",Array("Home",imgPath))
(Me).As(JavaObject).RunMethod("addListener",Array(btn))
Form1.RootPane.AddNode(btn,60,30,0,0)
Private Sub btn_click(msg As String, caption As String)
    Log($"Button with text  '${caption}'  was clicked"$)
End Sub
#if java
import javafx.scene.control.Button;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;

import javafx.scene.image.Image;
import javafx.scene.image.ImageView;

import java.io.FileInputStream;
import anywheresoftware.b4a.keywords.Common;
 public static Button createButtonWithImage(String caption, String imgPath) throws Exception {
        FileInputStream input = new FileInputStream(imgPath);
        Image image = new Image(input);
        ImageView imageView = new ImageView(image);
        Button button = new Button(caption, imageView);
        return button;
    }
public static void addListener(Button btn){
         btn.setOnAction(new EventHandler<ActionEvent>() {
            public void handle(ActionEvent e) {
                 String msg="clicked";
                ba.raiseEvent(this, "btn_click", msg, btn.getText());
            }
        });
 }  
#End If
 
Top