In my
previous post, I explained how to create a button widget using Button
constructor. We can create a button with text + graphic content (image icon)
using below Button constructor.
public
Button(String text, Node graphic)
Ex
InputStream
is = new FileInputStream(imageFilePath);
Image
image = new Image(is);
Button
button = new Button("Search Button3", new ImageView(image));
Button
class also provides 'setGraphic' method to set the icon to a button.
Ex
InputStream
is = new FileInputStream(imageFilePath);
Image
image = new Image(is);
Button
button = new Button("Search Button");
button.setGraphic(new
ImageView(image));
Find the
below working application.
ButtonApp.java
package com.sample.demos; import static javafx.geometry.Pos.CENTER; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.InputStream; import javafx.application.Application; 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 ButtonApp extends Application { private static String imageFilePath = "C:\\Users\\krishna\\Documents\\Study\\javaFX\\search.png"; @Override public void start(Stage primaryStage) throws FileNotFoundException { InputStream is = new FileInputStream(imageFilePath); Image image = new Image(is); Button button = new Button("Search Button"); button.setGraphic(new ImageView(image)); VBox vBox = new VBox(10, button); vBox.setAlignment(CENTER); Scene scene = new Scene(vBox, 400, 400); /* Set the scene to primaryStage, and call the show method */ primaryStage.setTitle("JavaFX 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(ButtonApp.class, args); } }
No comments:
Post a Comment