我有一个弹出窗口,右键单击它会显示一个 TextField
。它会自动隐藏,但如果字段中的值不是数字,我想阻止它隐藏。根据一些验证,当点击离开时,如何使用“隐藏事件”。
这是我的代码:
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);
}
}
最佳答案
一种解决方案是向 TextField
添加一个监听器,该监听器将在验证时设置 Popup
autoHide 属性:
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 ;");
}
});
如果当前内容类型不是数字,则不允许隐藏弹出窗口
。
关于java - 如何拦截弹出窗口的隐藏以验证字段,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60728966/