trilogy :
I have a popup that shows a TextField
on the right click of it. It auto hides, but I want to prevent it from hiding if the value in the field is not a number. How do you consume the "hide event" when clicking away, based on some validation.
Here is my code:
import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.control.Label;
import javafx.scene.control.TextField;
import javafx.scene.input.MouseButton;
import javafx.scene.layout.HBox;
import javafx.scene.layout.StackPane;
import javafx.stage.Popup;
import javafx.stage.Stage;
import javafx.stage.WindowEvent;
import org.apache.commons.lang3.math.NumberUtils;
public class Test extends Application
{
@Override
public void start(Stage primaryStage)
{
HBox root = new HBox();
TextField textField = new TextField();
Popup popup = new Popup();
popup.setAutoHide(true);
popup.getContent().clear();
popup.getContent().addAll(textField);
popup.setOnCloseRequest((WindowEvent event) ->
{
if (NumberUtils.isParsable(textField.getText()))
{
System.out.println("is a number");
textField.setStyle(null);
} else
{
System.out.println("enter a number");
textField.setStyle("-fx-border-color: red ; -fx-border-width: 1px ;");
event.consume();
}
});
Label label = new Label("click here");
StackPane labelPane = new StackPane(label);
label.setOnMouseClicked(event ->
{
if (event.getButton() == MouseButton.SECONDARY)
{
if (!popup.isShowing())
{
popup.show(labelPane, event.getScreenX() + 10, event.getScreenY());
}
}
});
root.getChildren().add(labelPane);
Scene scene = new Scene(root, 300, 250);
primaryStage.setTitle("Hello World!");
primaryStage.setScene(scene);
primaryStage.show();
}
/**
* @param args the command line arguments
*/
public static void main(String[] args)
{
launch(args);
}
}
adxl :
One solution is to add a listener to the TextField
which will set the Popup
autoHide property upon validation :
textField.textProperty().addListener(c->
{
if(NumberUtils.isParsable(textField.getText()))
{
popup.setAutoHide(true);
textField.setStyle(null);
}else {
popup.setAutoHide(false);
textField.setStyle("-fx-border-color: red ; -fx-border-width: 1px ;");
}
});
This won't allow the Popup
to hide if the current content type is not a number.
Guess you like
Origin http://43.154.161.224:23101/article/api/json?id=300333&siteId=1