AskOverflow.Dev

AskOverflow.Dev Logo AskOverflow.Dev Logo

AskOverflow.Dev Navigation

  • 主页
  • 系统&网络
  • Ubuntu
  • Unix
  • DBA
  • Computer
  • Coding
  • LangChain

Mobile menu

Close
  • 主页
  • 系统&网络
    • 最新
    • 热门
    • 标签
  • Ubuntu
    • 最新
    • 热门
    • 标签
  • Unix
    • 最新
    • 标签
  • DBA
    • 最新
    • 标签
  • Computer
    • 最新
    • 标签
  • Coding
    • 最新
    • 标签
主页 / coding / 问题 / 79200593
Accepted
user1438038
user1438038
Asked: 2024-11-18 23:54:40 +0800 CST2024-11-18 23:54:40 +0800 CST 2024-11-18 23:54:40 +0800 CST

JavaFX 绑定用于选择特定的组合框值

  • 772

我的界面有两个输入字段:一个用于选择的组合框Country和一个复选框。

public class Country {
  private String name;

  public String getName() {
    return name;
  }
}

我只想启用复选框,如果在组合框中选择了特定值(例如Germany)。

BooleanBinding noCountryBinding = Binding.isNull(cmbCountry.valueProperty());
BooleanBinding isGermanyBinding = Binding.equal(cmbCountry.getSelectionModel().selectedProperty().get().getName(), "Germany"); // <- This does not work, what can I do instead?

cbxFreeShipping.disableProperty().bind(Bindings.or(noCountryBinding, Bindings.not(isGermanyBinding));

第一个绑定本身工作正常,但我不知道如何让第二个绑定依赖于组合框项目的 String 属性。我尝试了一种不同的方法,即在组合框上实现一个侦听器,但它当然只会在选定项目发生变化时触发。

java
  • 3 3 个回答
  • 51 Views

3 个回答

  • Voted
  1. James_D
    2024-11-19T01:15:35+08:002024-11-19T01:15:35+08:00

    在 JavaFX 19 及更高版本中,您可以使用ObservableValue.map(...):

    var selectedCountryName = cmbCountry.getSelectionModel().selectedItemProperty().map(Country::getName);
    // or
    // var selectedCountryName = cmbCountry.valueProperty().map(Country::getName);
    var germanyNotSelected = selectedCountryName.map(country -> ! "Germany".equals(country)).orElse(true);
    cbxFreeShipping.disableProperty().bind(germanyNotSelected);
    

    如果没有选择任何内容(或者如果从返回选定实例),则将selectedCountryName包含。nullCountrynullgetName()

    selectedCountryName.map(country -> ! "Germany".equals(country))如果null为selectedCountryName空,则为,否则包含的结果!"Germany".equals(country)。如果包含,则orElse(true)调用返回一个包含的值。trueselectedCountryNamenull

    这是一个完整的例子:

    import javafx.application.Application;
    import javafx.scene.Scene;
    import javafx.scene.control.CheckBox;
    import javafx.scene.control.ComboBox;
    import javafx.scene.control.ListCell;
    import javafx.scene.layout.VBox;
    import javafx.stage.Stage;
    
    public class HelloApplication extends Application {
    
        static class Country {
            private final String name;
            Country(String name) {
                this.name = name;
            }
    
            public String getName() {
                return name;
            }
        }
    
        @Override
        public void start(Stage stage)  {
            ComboBox<Country> cmbCountry = new ComboBox<>();
            cmbCountry.getItems().addAll(
                new Country("France"),
                new Country("Germany"),
                new Country("Spain")
            );
            cmbCountry.setCellFactory( _ -> createCountryCell());
            cmbCountry.setButtonCell(createCountryCell());
            CheckBox cbxFreeShipping = new CheckBox("Free Shipping");
            var selectedCountryName = cmbCountry.getSelectionModel().selectedItemProperty().map(Country::getName);
            var germanyNotSelected = selectedCountryName.map(country -> ! "Germany".equals(country)).orElse(true);
            cbxFreeShipping.disableProperty().bind(germanyNotSelected);
    
            VBox root = new VBox(5, cmbCountry, cbxFreeShipping);
            Scene scene = new Scene(root, 400, 400);
            stage.setScene(scene);
            stage.show();
        }
    
        private ListCell<Country> createCountryCell() {
            return new ListCell<>() {
                @Override
                protected void updateItem(Country item, boolean empty) {
                    super.updateItem(item, empty);
                    if (empty || item == null) {
                        setText(null);
                    } else {
                        setText(item.getName());
                    }
                }
            };
        }
    
        public static void main(String[] args) {
            launch();
        }
    }
    
    • 3
  2. Best Answer
    DaveB
    2024-11-19T00:36:59+08:002024-11-19T00:36:59+08:00

    最好Bindings.createBooleanBinding()只使用ComboBox.valueProperty()。然后,您可以编写一个Supplier将 的当前值评估ComboBox.valueProperty()为简单的可空 的String。

    这是 Kotlin,但概念相同:

    class ComboBoxExample0 : Application() {
    
        private val countries = FXCollections.observableArrayList(
            Country("Germany"),
            Country("France"), Country("Denmark")
        )
    
        override fun start(stage: Stage) {
            val scene = Scene(createContent(), 280.0, 300.0)
            stage.scene = scene
            stage.show()
        }
    
        private fun createContent(): Region = VBox(20.0).apply {
            val comboBox = ComboBox<Country>().apply {
                items = countries
            }
            children +=
                CheckBox("This is a CheckBox").apply {
                    disableProperty().bind(
                        Bindings.createBooleanBinding(
                            { (comboBox.value == null) || (comboBox.value.name == "Germany") },
                            comboBox.valueProperty()
                        )
                    )
                }
            children += comboBox
            padding = Insets(40.0)
        }
    }
    
    data class Country(val name: String)
    
    
    fun main() = Application.launch(ComboBoxExample0::class.java)
    

    这里的关键点是,在Bindings.createBinding()调用中,依赖关系是 ,comboBox.valueProperty()这意味着Binding将在每次更改时失效comboBox.valueProperty()。然后 中的代码Supplier将只查看comboBox.value,这相当于comboBox.valueProperty().getValue(),它只是一个(可空)字符串。

    您可以使用 Fluent API 来实现,但随后您需要将其ObservableValue.map()用作。但随后您需要将其转换为 才能使用 Fluent API,因为映射将返回。这并不难,但方法更简洁。Country.nameObservableValueObservableStringValueObservableValue<String>Bindings.createBooleanBinding()

    • 2
  3. user1438038
    2024-11-19T18:28:08+08:002024-11-19T18:28:08+08:00

    为了完整起见,我想添加迄今为止已提交并经过我测试的两种解决方案。首先,这两种方法都有效!由于@DaveB 发布了 Kotlin 代码,因此这里有一个 Java 等效代码:

    BooleanBinding noFreeShipping = Bindings.createBooleanBinding(() -> {
        var noCountry = (null == cmbCountry.getValue());
        var isGermany = (null != cmbCountry.getValue() && "Germany".equals(cmbCountry.getValue().getName()));
    
        return (noCountry || !isGermany);
    }, cmbCountry.valueProperty());
    cbxFreeShipping.disableProperty().bind(noFreeShipping);
    

    在我看来,这个实现更容易阅读和理解。

    @James_D 提交的解决方案也有效,并且稍微简短一些:

    var selectedCountryName = cmbCountry.valueProperty().map(Country::getName);
    var isNotGermany = selectedCountryName.map(country -> ! "Germany".equals(country)).orElse(true);
    cbxFreeShipping.disableProperty().bind(isNotGermany);
    

    但是,由于的性质,我觉得阅读起来有点困难map()。此外,没有选择国家/地区的情况也不是那么明确。从技术角度来看,不确定哪种解决方案更好,但我认为我会坚持第一种实现方式。- 尽管如此,我很欣赏这两个答案!

    • 0

相关问题

  • Lock Condition.notify 抛出 java.lang.IllegalMonitorStateException

  • 多对一微服务响应未出现在邮递员中

  • 自定义 SpringBoot Bean 验证

  • Java 套接字是 FIFO 的吗?

  • 为什么不可能/不鼓励在服务器端定义请求超时?

Sidebar

Stats

  • 问题 205573
  • 回答 270741
  • 最佳答案 135370
  • 用户 68524
  • 热门
  • 回答
  • Marko Smith

    Vue 3:创建时出错“预期标识符但发现‘导入’”[重复]

    • 1 个回答
  • Marko Smith

    为什么这个简单而小的 Java 代码在所有 Graal JVM 上的运行速度都快 30 倍,但在任何 Oracle JVM 上却不行?

    • 1 个回答
  • Marko Smith

    具有指定基础类型但没有枚举器的“枚举类”的用途是什么?

    • 1 个回答
  • Marko Smith

    如何修复未手动导入的模块的 MODULE_NOT_FOUND 错误?

    • 6 个回答
  • Marko Smith

    `(表达式,左值) = 右值` 在 C 或 C++ 中是有效的赋值吗?为什么有些编译器会接受/拒绝它?

    • 3 个回答
  • Marko Smith

    何时应使用 std::inplace_vector 而不是 std::vector?

    • 3 个回答
  • Marko Smith

    在 C++ 中,一个不执行任何操作的空程序需要 204KB 的堆,但在 C 中则不需要

    • 1 个回答
  • Marko Smith

    PowerBI 目前与 BigQuery 不兼容:Simba 驱动程序与 Windows 更新有关

    • 2 个回答
  • Marko Smith

    AdMob:MobileAds.initialize() - 对于某些设备,“java.lang.Integer 无法转换为 java.lang.String”

    • 1 个回答
  • Marko Smith

    我正在尝试仅使用海龟随机和数学模块来制作吃豆人游戏

    • 1 个回答
  • Martin Hope
    Aleksandr Dubinsky 为什么 InetAddress 上的 switch 模式匹配会失败,并出现“未涵盖所有可能的输入值”? 2024-12-23 06:56:21 +0800 CST
  • Martin Hope
    Phillip Borge 为什么这个简单而小的 Java 代码在所有 Graal JVM 上的运行速度都快 30 倍,但在任何 Oracle JVM 上却不行? 2024-12-12 20:46:46 +0800 CST
  • Martin Hope
    Oodini 具有指定基础类型但没有枚举器的“枚举类”的用途是什么? 2024-12-12 06:27:11 +0800 CST
  • Martin Hope
    sleeptightAnsiC `(表达式,左值) = 右值` 在 C 或 C++ 中是有效的赋值吗?为什么有些编译器会接受/拒绝它? 2024-11-09 07:18:53 +0800 CST
  • Martin Hope
    The Mad Gamer 何时应使用 std::inplace_vector 而不是 std::vector? 2024-10-29 23:01:00 +0800 CST
  • Martin Hope
    Chad Feller 在 5.2 版中,bash 条件语句中的 [[ .. ]] 中的分号现在是可选的吗? 2024-10-21 05:50:33 +0800 CST
  • Martin Hope
    Wrench 为什么双破折号 (--) 会导致此 MariaDB 子句评估为 true? 2024-05-05 13:37:20 +0800 CST
  • Martin Hope
    Waket Zheng 为什么 `dict(id=1, **{'id': 2})` 有时会引发 `KeyError: 'id'` 而不是 TypeError? 2024-05-04 14:19:19 +0800 CST
  • Martin Hope
    user924 AdMob:MobileAds.initialize() - 对于某些设备,“java.lang.Integer 无法转换为 java.lang.String” 2024-03-20 03:12:31 +0800 CST
  • Martin Hope
    MarkB 为什么 GCC 生成有条件执行 SIMD 实现的代码? 2024-02-17 06:17:14 +0800 CST

热门标签

python javascript c++ c# java typescript sql reactjs html

Explore

  • 主页
  • 问题
    • 最新
    • 热门
  • 标签
  • 帮助

Footer

AskOverflow.Dev

关于我们

  • 关于我们
  • 联系我们

Legal Stuff

  • Privacy Policy

Language

  • Pt
  • Server
  • Unix

© 2023 AskOverflow.DEV All Rights Reserve