我有一个 JavaFX 自定义对话框,其中有
TextField
以及使用 TextFormatter
的 IntegerStringConverter
。我成功地将输入限制为数字,因此 TextField
的内容绝对是一个整数(好吧,它可能超出范围 - 接下来我将穿过那座桥)。
我的问题是如何将 TextField
的值
in 和 out获取为整数。我能找到的所有方法和成员仍然期望或返回
String
。 TextFormatter
仅用于绑定,还是有某种方法可以读取和写入整数值?
这是自定义对话框的控制器(我懒得显示
numberValidationFormatter
,因为它非常标准):
package org.eu.tr480_free.stitcher
import javafx.fxml.FXML
import javafx.fxml.FXMLLoader
import javafx.scene.control.*
import javafx.stage.Modality
import javafx.stage.Window
import javafx.util.converter.IntegerStringConverter
import org.eu.tr480_free.stitcher.View.numberValidationFormatter
import java.io.IOException
class NewFileDlg(val window: Window) : Dialog<ButtonType>() {
@FXML
lateinit var FabricCombo: ComboBox<FabricType>
@FXML
lateinit var rows: TextField
@FXML
lateinit var columns: TextField
init {
try {
val loader = FXMLLoader()
loader.location = javaClass.getResource("new_file_dialog.fxml")
loader.setController(this)
initOwner(window)
initModality(Modality.APPLICATION_MODAL)
isResizable = false
title = "New File"
dialogPane = loader.load()
rows.textFormatter = TextFormatter(IntegerStringConverter(), 0, numberValidationFormatter())
columns.textFormatter= TextFormatter(IntegerStringConverter(), 0, numberValidationFormatter())
}
catch (e: IOException) {
throw RuntimeException("Unable to load asset: new file dialog")
}
for (f in FabricType.values()) {
FabricCombo.items.add(f)
}
}
}
您可以通过请求从文本格式化程序中获取值。
我会用 Java 提供答案,因为我不写 Kotlin。
TextFormatter
一般会输入其正在格式化的类型,在本例中为 Integer
。
getValue
来从格式化程序获取值。这将返回为格式化程序指定的特定类型的值。
为此,您必须拥有对可以调用
getValue
的格式化程序的引用。您可以存储引用(就像我在下面的代码中所做的那样),也可以在需要时向文本字段询问其格式化程序。
格式化程序中的值是一个属性,因此您可以绑定到它。您还可以将其设置为间接更改文本字段中的文本以匹配设置值。
对于下面的示例,我在用户输入时不将用户输入限制为有效整数,因为这与从格式化程序获取值无关。
要使用该示例,请运行应用程序,在文本字段中输入整数值,然后按 Enter 键确认该值。标签将侦听文本格式化程序中值的更改,从文本格式化程序中获取更改后的值,将整数值转换为字符串,然后将标签的文本设置为转换后的字符串。
import javafx.application.Application;
import javafx.geometry.Insets;
import javafx.scene.Scene;
import javafx.scene.control.*;
import javafx.scene.layout.VBox;
import javafx.stage.Stage;
import javafx.util.converter.IntegerStringConverter;
public class TextFormatterApp extends Application {
public static void main(String[] args) {
launch(args);
}
public void start(Stage stage) throws Exception {
Label fieldValue = new Label();
TextField formattedField = new TextField();
TextFormatter<Integer> integerTextFormatter = new TextFormatter<>(
new IntegerStringConverter()
);
formattedField.setTextFormatter(
integerTextFormatter
);
integerTextFormatter.valueProperty().addListener((observable, oldValue, newValue) -> {
fieldValue.setText(
Integer.toString(
integerTextFormatter.getValue()
)
);
});
VBox layout = new VBox(10, formattedField, fieldValue);
layout.setPadding(new Insets(10));
stage.setScene(new Scene(layout));
stage.show();
}
}