JavaFX Button position the text under the image

Introduction

To position the text under the image in image button in JavaFX

// Position the text under the image.
ok.setContentDisplay(ContentDisplay.TOP);
cancel.setContentDisplay(ContentDisplay.TOP);
    

Full source

// Use an image with a button. 

import javafx.application.Application;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.geometry.Pos;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.ContentDisplay;
import javafx.scene.control.Label;
import javafx.scene.image.ImageView;
import javafx.scene.layout.FlowPane;
import javafx.stage.Stage;

public class Main extends Application {
  private Label response;
  public static void main(String[] args) {
    launch(args);//from   w  ww.ja v  a2 s. c o  m
  }

  public void start(Stage myStage) {
    myStage.setTitle("Use Images with Buttons");

    FlowPane rootNode = new FlowPane(10, 10);

    rootNode.setAlignment(Pos.CENTER);

    Scene myScene = new Scene(rootNode, 250, 450);

    myStage.setScene(myScene);

    // Create a label.
    response = new Label("Push a Button");

    // Create two image-based buttons.
    Button ok = new Button("OK", new ImageView("OK.png"));
    Button cancel = new Button("Cancel", new ImageView("Cancel.png"));

    // Position the text under the image.
    ok.setContentDisplay(ContentDisplay.TOP);
    cancel.setContentDisplay(ContentDisplay.TOP);

    // Handle the action events for the OK button.
    ok.setOnAction(new EventHandler<ActionEvent>() {
      public void handle(ActionEvent ae) {
        response.setText("OK Pressed");
      }
    });

    // Handle the action events for the cancel button.
    cancel.setOnAction(new EventHandler<ActionEvent>() {
      public void handle(ActionEvent ae) {
        response.setText("Cancel Pressed");
      }
    });

    // Add the label and buttons to the scene graph.
    rootNode.getChildren().addAll(ok, cancel, response);

    myStage.show();
  }
}



PreviousNext

Related