JavaFX Tutorial - Java Button(java.lang.String text, Node graphic) Constructor








Syntax

Button(java.lang.String text, Node graphic) constructor from Button has the following syntax.

public Button(java.lang.String text,
  Node graphic)

Example

In the following code shows how to use Button.Button(java.lang.String text, Node graphic) constructor.

//from ww w .ja  v  a2s .  c o  m
import javafx.application.Application;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.scene.Group;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
import javafx.scene.layout.VBox;
import javafx.stage.Stage;

public class Main extends Application {

    public static void main(String[] args) {
        launch(args);
    }

    @Override
    public void start(Stage stage) {
        Scene scene = new Scene(new Group());
        stage.setTitle("Button Sample");
        stage.setWidth(300);
        stage.setHeight(190);

        VBox vbox = new VBox();
        vbox.setLayoutX(20);
        vbox.setLayoutY(20);

        Image image = new Image(getClass().getResourceAsStream("a.png"));
        Button button1 = new Button("Accept",new ImageView(image));
        button1.setOnAction(new EventHandler<ActionEvent>() {
            @Override public void handle(ActionEvent e) {
                System.out.println("Accepted");
            }
        });

        vbox.getChildren().add(button1);
        vbox.setSpacing(10);
        ((Group)scene.getRoot()).getChildren().add(vbox);

        stage.setScene(scene);
        stage.show();
    }
}