Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
How to add an image to a button (action) in JavaFX?
A button controls in user interface applications, in general, on clicking the button it performs the respective action. You can create a Button by instantiating the javafx.scene.control.Button class.
Adding image to a button
You can add a graphic object (node) to a button using the setGraphic() method of the Button class (inherited from javafx.scene.control.Labeled class). This method accepts an object of the Node class representing a graphic (icon).
To add an image to a button −
Create an Image object bypassing the path for the required graphic.
Create an ImageView object using the image object.
Create a button by instantiating the Button class.
Finally, invoke the setGraphic() method on the button by passing the ImageView object as a parameter.
Example
import javafx.application.Application;
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.paint.Color;
import javafx.stage.Stage;
public class ButtonGraphis extends Application {
public void start(Stage stage) {
//Creating a graphic (image)
Image img = new Image("UIControls/logo.png");
ImageView view = new ImageView(img);
view.setFitHeight(80);
view.setPreserveRatio(true);
//Creating a Button
Button button = new Button();
//Setting the location of the button
button.setTranslateX(200);
button.setTranslateY(25);
//Setting the size of the button
button.setPrefSize(80, 80);
//Setting a graphic to the button
button.setGraphic(view);
//Setting the stage
Group root = new Group(button);
Scene scene = new Scene(root, 595, 170, Color.BEIGE);
stage.setTitle("Button Graphics");
stage.setScene(scene);
stage.show();
}
public static void main(String args[]){
launch(args);
}
}
Output

Advertisements