
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
Add Image as Label Using JavaFX
You can display a text element/image on the User Interface using the Label component. It is a not editable text control, mostly used to specify the purpose of other nodes in the application.
In JavaFX you can create a label by instantiating the javafx.scene.control.Label class. To create a label, you need to instantiate this class
You can use a graphic object as a label using the setGraphic() method of the Label class (inherited from javafx.scene.control.Labeled class). This method accepts an object of the Node class representing a graphic (icon).
Example
import javafx.application.Application; import javafx.scene.Group; import javafx.scene.Scene; import javafx.scene.control.Label; import javafx.scene.image.Image; import javafx.scene.image.ImageView; import javafx.scene.paint.Color; import javafx.scene.text.Font; import javafx.scene.text.FontPosture; import javafx.scene.text.FontWeight; import javafx.stage.Stage; public class ImageAsLabel extends Application { public void start(Stage stage) { // Creating a Label Label label = new Label("Sample label"); // Creating a graphic (image) Image img = new Image("UIControls/logo.png"); ImageView view = new ImageView(img); view.setFitHeight(80); view.setPreserveRatio(true); label.setGraphic(view); // Setting font to the label Font font = Font.font("Brush Script MT", FontWeight.BOLD, FontPosture.REGULAR, 25); label.setFont(font); // Filling color to the label label.setTextFill(Color.BROWN); // Setting the position label.setTranslateX(150); label.setTranslateY(25); Group root = new Group(); root.getChildren().add(label); // Setting the stage Scene scene = new Scene(root, 595, 200, Color.BEIGE); stage.setTitle("Label Example"); stage.setScene(scene); stage.show(); } public static void main(String args[]){ launch(args); } }
Output
On execution, it will produce the following output:
Advertisements