繁体   English   中英

您如何通过Java FX中的多个事件处理程序执行一项操作?

[英]How do you do one action through multiple event handlers in Java FX?

我正在尝试做一个二次公式的形式。 它可以在命令提示符下运行,但是我希望它可以在表单上运行,并在每次更改输入时更新输出。 到目前为止,这是我的表格。 您可以更改多个区域,它们是组合框和文本字段,但是我希望所有这些区域都更新标签以显示输出。 这是我的问题所在。 我不知道该如何使用类似于更新标签的方法。 下面是该代码的简化版本:

import javafx.application.Application;
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.GridPane;
import javafx.stage.Stage;

public class SmallForm extends Application{

    public static void main(String[] args) {
        launch(args);
    }

    @Override
    public void start(Stage primaryStage) throws Exception {
        GridPane grid = new GridPane();
        grid.setVgap(5);

        Label lblConcatenated = new Label("");//label that will hold the concatenated string
        grid.add(lblConcatenated, 0, 0);

        TextField txtA = new TextField("");//Text field one
        grid.add(txtA, 0, 1);

        TextField txtB = new TextField("");//Text field two
        grid.add(txtB, 0, 2);

        txtA.textProperty().addListener(new ChangeListener<String>() { //Triggers whenever the second text field is changed
            @Override public void changed(ObservableValue ov, String t, String t1) {
               lblConcatenated.setText(txtA.getText() + txtB.getText());//Concatenates the text in the two text fields
            }
        });

        txtB.textProperty().addListener(new ChangeListener<String>() {
            @Override public void changed(ObservableValue ov, String t, String t1) { //Triggers whenever the second text field is changed
                lblConcatenated.setText(txtA.getText() + txtB.getText());//Concatenates the text in the two text fields
            }
        });

        Scene scene = new Scene(grid, 250, 100);
        primaryStage.setScene(scene);
        primaryStage.show();
    }
}

我的目标是使连接行仅需写入一次。 重复更多的代码,这将更加普遍。 在命令提示符下,可以使用一种方法轻松完成此操作,但据我所知在java fx中不起作用。 我听说过用于执行此操作的术语,但我无法弄清楚。

谢谢!

您当然可以使用一种方法。 您还可以对两个属性使用相同的ChangeListener<String>对象。

但是,在这种情况下,我建议使用绑定:

lblConcatenated.textProperty().bind(txtA.textProperty().concat(txtB.textProperty()));

如果您需要解析值并根据解析后的值进行更新,建议使用TextFormatter

StringConverter<Double> converter = new DoubleStringConverter();
TextFormatter<Double> formatterA = new TextFormatter<>(converter, 0d);
TextFormatter<Double> formatterB = new TextFormatter<>(converter, 0d);
txtA.setTextFormatter(formatterA);
txtB.setTextFormatter(formatterB);

formatterA.valueProperty()...

TextField失去焦点或触发TextFieldonAction事件时,格式器值将更新。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM