【问题标题】:Complex binding situation复杂的绑定情况
【发布时间】:2019-04-11 08:31:40
【问题描述】:

在 javafx 场景中,我有:

  • 包含一些语言环境作为项目的组合框

  • 带有条目(区域设置、字符串)的哈希表

  • 显示和编辑文本的文本字段

我想做的是:

  • 当区域设置组合框改变时,textield 会根据选择的定位显示存储在哈希表中的文本。示例 1:如果选择了法语,则文本字段显示“法语文本”。示例 2:如果选择了中文,则 textfield 不显示任何内容(哈希表不包含 zh 键)。

  • 当在文本字段中键入一些文本时,哈希表会使用组合框中选择的语言环境执行 put。示例 1:如果键入了“aaa”并选择了法语,则哈希表使用文本“aaa”修改条目 fr。示例 2:如果输入了 'bbb' 并选择了 chinese,则可以添加条目 (zh,'bbb')。示例 3:如果 textfiled 没有文本并且选择了英语,则 hashtable 删除 en 条目。

最初哈希表没有空字符串,并且组合框总是选择一个定位。有没有可能做到这一点?

【问题讨论】:

  • 您可以在属性之间进行绑定,因为Hashtable 不是javafx.beans.property.Property,您希望如何实现?

标签: java binding javafx-8


【解决方案1】:

通过在Hashtable 中使用String 对象,您不能使用任何Property 的绑定方法与之交互,但您仍然应该能够通过在这些属性上使用侦听器来实现您的目标。这是一个粗略的例子:

public class Controller {

    private VBox base = new VBox();
    private ComboBox<Locale> comboBox = new ComboBox<>();
    private TextField textField = new TextField();
    private Button button = new Button("Print");

    private Hashtable<Locale, String> map = new Hashtable<>();

    public VBox getBase() {
        return base;
    }

    public Controller() {
        setupUi();

        addItem("Chinese");
        addItem("French");
        addItem("English");
        comboBox.getItems().add(new Locale("Russia", "Some Russian Text"));

        comboBox.getSelectionModel().selectedItemProperty()
                .addListener((obs, oldVal, newVal) -> textField.setText(map.get(newVal)));

        textField.textProperty().addListener((obs, oldVal, newVal) -> {
            if (newVal == null || newVal.equals("")) {
                map.remove(comboBox.getValue());
            } else {
                map.put(comboBox.getValue(), newVal);
            }
        });

        comboBox.getSelectionModel().selectFirst();
    }

    private void setupUi() {
        base.getChildren().addAll(comboBox, textField, button);
        button.setOnAction(event -> System.out.println(map));
    }

    private void addItem(String name) {
        Locale locale = new Locale(name, String.format("Some %s text", name));
        map.put(locale, locale.text);
        comboBox.getItems().add(locale);
    }

}


class Locale {

    String name;
    String text;

    Locale(String name, String text) {
        this.name = name;
        this.text = text;
    }

    @Override
    public String toString() {
        return name;
    }

}

【讨论】:

    猜你喜欢
    • 2017-12-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-09-05
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多