JavaFX:检查文本属性是否为空(而不仅仅是空) [英] JavaFX: check whether a text property is blank (and not just empty)

查看:212
本文介绍了JavaFX:检查文本属性是否为空(而不仅仅是空)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我希望根据文本字段是否包含任何内容启用或禁用按钮,我想通过使用属性绑定来实现它。

I want to have a button enabled or disabled based on whether a text field contains anything, and I want to implement this by using property binding.

所以首先我在文本字段的text属性上使用isEmpty()方法为按钮的disabled属性创建一个布尔绑定:

So at first I used the isEmpty() method on the text field's text property to create a boolean binding for the button's disabled property:

startSearchButton.disableProperty().bind(searchField.textProperty().isEmpty());

虽然绑定有效,但我对文本字段包含任何内容的定义与isEmpty不同( )方法确实,即只是检查文本的长度是否> 0.但是,我对是否存在真实文本感兴趣,即文本字段是否为空白(不仅仅是空的,但实际上不仅仅是空格。)

While the binding works, my definition of "text field contains anything" is different to what the isEmpty() method does, namely just checking if the text's length is > 0. However, I'm interested in whether there is "real" text, i.e. whether the text field is blank (not just not empty, but actually not only whitespace).

不幸的是没有方法isBlank(),我也找不到Bindings实用程序类中的任何适当的东西。现在我看到你可以通过Bindings.createBooleanProperty方法实现你喜欢的任何自定义布尔属性,但我还不熟悉定义自定义绑定的概念。我如何为我的情况实现这样的布尔属性?

Unfortunately there is no method isBlank(), and I also couldn't find anything appropriate in the Bindings utility class. Now I saw that you can implement any custom boolean property you like via the Bindings.createBooleanProperty method, but I'm not yet familiar with the concept of defining custom bindings. How would I have to implement such a boolean property for my case?

推荐答案

您可以使用(在许多方法中)创建自定义绑定) Bindings.createBooleanBinding(...) 。第一个参数是一个计算绑定值的函数(你可以用 trim()修剪文本中的空格,然后检查结果是否为空);其余参数是触发重新计算绑定的可观察对象列表。您希望在文本字段中的文本更改时重新计算绑定,因此只需指定text属性:

You can create a custom binding using (among many methods) Bindings.createBooleanBinding(...). The first argument is a function that computes the value of the binding (you can trim whitespace from the text with trim() and then check if the result is empty); the remaining arguments are a list of observables that trigger recomputation of the binding. You want to recompute the binding when the text in the text field changes, so just specify the text property:

startSearchButton.disableProperty().bind(Bindings.createBooleanBinding(() -> 
    searchField.getText().trim().isEmpty(),
    searchField.textProperty());

这篇关于JavaFX:检查文本属性是否为空(而不仅仅是空)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆