Sunday, 27 May 2018

JavaFX: Add an image to radio button

By using 'setGraphic' method, you can add graphic icon to the radio button.

Ex
RadioButton radioButton = new RadioButton();
radioButton.setText("Java");

/* Add an image to radio button */
InputStream is = new FileInputStream(imageFilePath);
Image image = new Image(is);
radioButton.setGraphic(new ImageView(image));

Find the below working application.

RadioButtonApp.java
package com.sample.demos;

import static javafx.geometry.Pos.CENTER;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.InputStream;
import java.net.MalformedURLException;

import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.control.RadioButton;
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
import javafx.scene.layout.VBox;
import javafx.stage.Stage;

public class RadioButtonApp extends Application {
 private static String imageFilePath = "C:\\Users\\krishna\\Documents\\Study\\javaFX\\javaIcon.png";

 @Override
 public void start(Stage primaryStage) throws FileNotFoundException, MalformedURLException {
  RadioButton radioButton = new RadioButton();
  radioButton.setText("Java");

  /* Add an image to radio button */
  InputStream is = new FileInputStream(imageFilePath);
  Image image = new Image(is);
  radioButton.setGraphic(new ImageView(image));

  VBox vBox = new VBox(10, radioButton);
  vBox.setAlignment(CENTER);

  Scene scene = new Scene(vBox, 400, 400);

  /* Set the scene to primaryStage, and call the show method */
  primaryStage.setTitle("JavaFX Radio Button Example");
  primaryStage.setScene(scene);
  primaryStage.show();
 }

}

TestFX.java
package com.sample.demos;

import javafx.application.Application;

public class TestFX {
 public static void main(String args[]) {
  Application.launch(RadioButtonApp.class, args);
 }
}


Previous                                                 Next                                                 Home

No comments:

Post a Comment