Is it possible to bind a StringProperty to a POJO's String in JavaFX?

孤街浪徒 提交于 2019-11-28 09:30:42

You can obviously set the values in Entity without doing anything except using a listener in JavaFX. If you want to go the other way you can add java.beans.PropertyChangeSupport. It's not in a javafx package.

package bindpojo;

import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import java.beans.PropertyChangeSupport;
import javafx.application.Application;
import javafx.beans.property.SimpleStringProperty;
import javafx.beans.property.StringProperty;
import javafx.beans.value.ChangeListener;
import javafx.beans.value.ObservableValue;
import javafx.scene.Scene;
import javafx.scene.control.Label;
import javafx.scene.control.TextField;
import javafx.scene.layout.VBox;
import javafx.stage.Stage;

public class BindPojo extends Application {
    StringProperty fxString = new SimpleStringProperty();
    StringProperty tmpString = new SimpleStringProperty();

    @Override
    public void start(Stage primaryStage) {
        VBox vbox = new VBox();
        TextField text = new TextField();
        Label label1 = new Label();
        Label label2 = new Label();
        Entity entity = new Entity("");
        vbox.getChildren().addAll(text,label1,label2);
        Scene scene = new Scene(vbox, 300, 200);
        primaryStage.setScene(scene);
        primaryStage.show();

        fxString.bindBidirectional(text.textProperty());

        fxString.addListener(new ChangeListener<String>() {
            @Override
            public void changed(ObservableValue<? extends String> observable, String oldValue, String newValue) {
                entity.setValue(newValue);
                label1.setText(entity.getValue());
            }
        });

        entity.addPropertyChangeListener(new PropertyChangeListener() {
            @Override
            public void propertyChange(PropertyChangeEvent evt) {
                tmpString.set(evt.getNewValue().toString());
            }
        });

        label2.textProperty().bind(tmpString);
    }

    public class Entity {
    private String m_Value;
    private final PropertyChangeSupport pcs = new PropertyChangeSupport(this);
    public Entity(String value) { m_Value = value; }
    public String getValue() { return m_Value; }
    public void setValue(String value) {
        pcs.firePropertyChange("m_Value", m_Value, value);
        m_Value = value;
    }
    public void addPropertyChangeListener(PropertyChangeListener listener) {
                    pcs.addPropertyChangeListener(listener);
                }
    }
}

You don't really need the tmpString, I just used used it in case you want to have Entity resemble a javafx string property. You could just set the label in the property change listener instead of setting a string property and then binding to it.

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!