[英]How can i create a javafx dialog box to update value?
我想在 javafx 中創建一個對話框,並允許它在每次定義變量的值小於 1 時彈出,並在 dialogbx 文本字段的幫助下,接受大於 1 的新值並更新該值。 有些我無法讓它工作,任何幫助將不勝感激。
TextInputDialog dialog = new TextInputDialog("Enter value");
dialog.setTitle("Text Input Dialog");
dialog.setHeaderText("Look, a Text Input Dialog");
dialog.setContentText("Please enter value:");
Optional<String> result = dialog.showAndWait();
if (result.isPresent()){
Apple.value= Apple.value+result.get());
}
當您使用標准TextInputDialog
時,您將獲得一個TextField
以便您需要檢查用戶輸入是否是有效的可解析數字。 這是一個帶有IntegerProperty
的小例子:
Controller Class:
package sample;
import javafx.beans.property.IntegerProperty;
import javafx.beans.property.SimpleIntegerProperty;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.scene.control.Label;
import javafx.scene.control.TextInputDialog;
import java.net.URL;
import java.util.Optional;
import java.util.ResourceBundle;
public class Controller implements Initializable {
@FXML
private Label currentValueLabel;
private IntegerProperty value = new SimpleIntegerProperty(1);
@Override
public void initialize(URL location, ResourceBundle resources) {
// Label to show the current value:
currentValueLabel.textProperty().bind(value.asString("Current value: %d"));
// Add a listener to the value property:
value.addListener((observable, oldValue, newValue) -> {
// Show dialog as long as a valid input was made:
while (value.get() < 1) {
TextInputDialog dialog = new TextInputDialog("1");
dialog.setTitle("Text Input Dialog");
dialog.setHeaderText("Look, a Text Input Dialog");
dialog.setContentText("Please enter value:");
Optional<String> result = dialog.showAndWait();
if (result.isPresent()) {
int input;
try {
// Parse the user input:
input = Integer.parseInt(result.get());
if (input < 1) {
// User entered an integer value but less than 1:
System.err.println("Invalid value: " + input);
} else {
// User entered a valid value:
this.value.set(input);
}
} catch (NumberFormatException e) {
// Could not parse user input:
System.err.println("Parse error " + e.getMessage());
}
}
}
});
}
@FXML
public void handleChangeValueBtnClick() {
// Change the value to zero which triggers the listener:
value.set(0);
}
}
FXML 文件:
<?xml version="1.0" encoding="UTF-8"?>
<?import javafx.scene.control.Button?>
<?import javafx.scene.control.Label?>
<?import javafx.scene.layout.VBox?>
<VBox xmlns="http://javafx.com/javafx/11.0.1" xmlns:fx="http://javafx.com/fxml/1" fx:controller="sample.Controller">
<children>
<Label fx:id="currentValueLabel" text="Current value: " />
<Button mnemonicParsing="false" onAction="#handleChangeValueBtnClick" text="Change value to zero" />
</children>
</VBox>
您還可以使用定義最小值的Spinner
控件創建自定義對話框,以便用戶只能輸入有效值。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.