Wednesday 9 May 2018

JavaFX: Working with Label widget

Label is used to display non-editable text in the user interface.

How to create Label?
Label class provides below constructors to define label widget.

public Label()
public Label(String text)
public Label(String text, Node graphic)

Ex
Label label1 = new Label();
label1.setText("Hello JavaFX");

Label label2 = new Label("Good Morning");

InputStream is = new FileInputStream(imageFilePath);
Image image = new Image(is);
Label label3 = new Label("Java Icon", new ImageView(image));

Find the below working application.

LabelApp.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.Label;
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
import javafx.scene.layout.VBox;
import javafx.stage.Stage;

public class LabelApp extends Application {

 private static String imageFilePath = "C:\\Users\\krishna\\Documents\\Study\\javaFX\\javaIcon.png";

 @Override
 public void start(Stage primaryStage) throws FileNotFoundException {

  Label label1 = new Label();
  label1.setText("Hello JavaFX");

  Label label2 = new Label("Good Morning");

  InputStream is = new FileInputStream(imageFilePath);
  Image image = new Image(is);
  Label label3 = new Label("Java Icon", new ImageView(image));

  VBox vBox = new VBox(10, label1, label2, label3);
  vBox.setAlignment(CENTER);

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

  /* Set the scene to primaryStage, and call the show method */
  primaryStage.setTitle("JavaFX Label 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(LabelApp.class, args);
 }
}

When you ran above application, you can able to see below window.








      Working with Label widget
      Set label text color
      Set gap between text and graphic image
      Align label text
      setContentDisplay: Set the position of graphic relative to text
      setFont: Set label font
      Wrapping up the text
      Render big strings in limited space
      Applying Effects
      Event handling


Previous                                                 Next                                                 Home

No comments:

Post a Comment