0

Is it possible to create a Label(Non-editable text field) with a close button?

On button click, the label should disappear.

2 Answers 2

3

Joey's answer works, but note that you can embed the button inside the label by using it as the label's graphic:

import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.ContentDisplay;
import javafx.scene.control.Label;
import javafx.scene.layout.HBox;
import javafx.stage.Stage;

public class LabelWithCloseButton extends Application {

    @Override
    public void start(Stage primaryStage) {
        Button closeButton = new Button("X");

        // In real life, use an external style sheet rather than inline styles: 
        // I did it this way for brevity 
        closeButton.setStyle("-fx-font-size: 6pt; -fx-text-fill:red;");

        Label label = new Label("Click the button to close");
        label.setGraphic(closeButton);
        label.setContentDisplay(ContentDisplay.RIGHT);

        HBox root = new HBox(label);
        closeButton.setOnAction(event -> root.getChildren().remove(label));

        Scene scene = new Scene(root, 250, 150);
        primaryStage.setScene(scene);
        primaryStage.show();
    }

    public static void main(String[] args) {
        launch(args);
    }
}
0

Create a button and trigger which label to make invisible:

Button moveBut = new Button("Hide Label"); 
moveBut.setOnAction(new EventHandler<actionevent>() {

 @Override 
 public void handle(ActionEvent arg0) {  

     labelName.setVisible(false);

                                      } 

   });

Here is a Link which shows how to hide/un-hide Labels from different region using BorderPane layout.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.