gpt4 book ai didi

javafx - 带有数字和字母的字符串加倍 javafx

转载 作者:行者123 更新时间:2023-12-01 10:36:09 26 4
gpt4 key购买 nike

您好,我正在尝试从显示价格的文本字段中读取数字,例如£3.00,并将价格值转换为双倍。有什么办法吗

Double value;
value = Double.parseDouble(textField.getText());

但由于 £ 符号,它不允许我这样做。有没有办法去除井号然后读取数字。

谢谢

最佳答案

有一些 TextFormatter并更改内置于 JavaFX TextField API 中的过滤器处理逻辑,您可以利用它。

currency format

import javafx.application.Application;
import javafx.beans.binding.Bindings;
import javafx.geometry.Insets;
import javafx.scene.Scene;
import javafx.scene.control.*;
import javafx.scene.layout.VBox;
import javafx.stage.Stage;
import javafx.util.StringConverter;

import java.text.DecimalFormat;
import java.text.ParseException;

class CurrencyFormatter extends TextFormatter<Double> {
private static final double DEFAULT_VALUE = 5.00d;
private static final String CURRENCY_SYMBOL = "\u00A3"; // british pound

private static final DecimalFormat strictZeroDecimalFormat
= new DecimalFormat(CURRENCY_SYMBOL + "###,##0.00");

CurrencyFormatter() {
super(
// string converter converts between a string and a value property.
new StringConverter<Double>() {
@Override
public String toString(Double value) {
return strictZeroDecimalFormat.format(value);
}

@Override
public Double fromString(String string) {
try {
return strictZeroDecimalFormat.parse(string).doubleValue();
} catch (ParseException e) {
return Double.NaN;
}
}
},
DEFAULT_VALUE,
// change filter rejects text input if it cannot be parsed.
change -> {
try {
strictZeroDecimalFormat.parse(change.getControlNewText());
return change;
} catch (ParseException e) {
return null;
}
}
);
}
}

public class FormattedTextField extends Application {

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

@Override
public void start(final Stage stage) {
TextField textField = new TextField();
textField.setTextFormatter(new CurrencyFormatter());

Label text = new Label();
text.textProperty().bind(
Bindings.concat(
"Text: ",
textField.textProperty()
)
);

Label value = new Label();
value.textProperty().bind(
Bindings.concat(
"Value: ",
textField.getTextFormatter().valueProperty().asString()
)
);

VBox layout = new VBox(
10,
textField,
text,
value,
new Button("Apply")
);
layout.setPadding(new Insets(10));

stage.setScene(new Scene(layout));
stage.show();
}

}

DecimalFormat 的确切规则如果您对用户体验非常讲究(例如,用户可以输入货币符号吗?如果用户不输入货币符号会发生什么?是否允许空值?等等),过滤器可能会变得有点棘手。合理的用户体验和(相对)易于编程的解决方案之间的折衷。对于实际的生产级应用程序,您可能希望稍微调整一下逻辑和行为以适合您的特定应用程序。

请注意,应用按钮实际上不需要执行任何操作来应用更改。当用户将焦点从文本字段移开时(只要他们通过了更改过滤器),就会应用更改。因此,如果用户单击应用按钮,它会获得焦点,文本字段会失去焦点,并应用更改(如果适用)。

上面的示例将货币值视为双倍值(以匹配问题),但那些对货币很认真的人可能希望查看 BigDecimal .

有关使用类似概念的更简单的解决方案,另请参阅:

关于javafx - 带有数字和字母的字符串加倍 javafx,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35093145/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com