我有一个弹出窗口,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 ;");
}
});
Popup
如果当前内容类型不是数字,则这将不允许隐藏。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句