带有数字和字母的字符串将 javafx 加倍 [英] String with numbers and letters to double javafx

查看:25
本文介绍了带有数字和字母的字符串将 javafx 加倍的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试从显示价格的文本字段中读取数字,例如3.00 英镑,并将价格值转换为双倍.有办法吗

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

但由于 £ 符号,它不会让我这样做.有没有办法去掉井号然后读取数字.

谢谢

解决方案

有一些

import javafx.application.Application;导入 javafx.beans.binding.Bindings;导入 javafx.geometry.Insets;导入 javafx.scene.Scene;导入 javafx.scene.control.*;导入 javafx.scene.layout.VBox;导入 javafx.stage.Stage;导入 javafx.util.StringConverter;导入 java.text.DecimalFormat;导入 java.text.ParseException;CurrencyFormatter 类扩展了 TextFormatter{私人静态最终双 DEFAULT_VALUE = 5.00d;private static final String CURRENCY_SYMBOL = "u00A3";//英镑private static final DecimalFormat strictZeroDecimalFormat= new DecimalFormat(CURRENCY_SYMBOL + "###,##0.00");CurrencyFormatter() {极好的(//字符串转换器在字符串和值属性之间进行转换.new StringConverter() {@覆盖公共字符串 toString(双值){返回 strictZeroDecimalFormat.format(value);}@覆盖公共双从字符串(字符串字符串){尝试 {return strictZeroDecimalFormat.parse(string).doubleValue();} catch (ParseException e) {返回 Double.NaN;}}},默认值,//如果无法解析,更改过滤器将拒绝文本输入.改变 ->{尝试 {strictZeroDecimalFormat.parse(change.getControlNewText());退换货;} catch (ParseException e) {返回空;}});}}公共类 FormattedTextField 扩展应用程序 {公共静态无效主(字符串 [] args){ 启动(参数);}@覆盖公共无效开始(最后阶段阶段){TextField textField = new TextField();textField.setTextFormatter(new CurrencyFormatter());标签文本=新标签();text.textProperty().bind(绑定.concat(文本: ",textField.textProperty()));标签值=新标签();value.textProperty().bind(绑定.concat(价值: ",textField.getTextFormatter().valueProperty().asString()));VBox 布局 = 新 VBox(10、文本域,文本,价值,新按钮(应用"));layout.setPadding(new Insets(10));stage.setScene(新场景(布局));舞台表演();}}

DecimalFormat 的确切规则如果您对用户体验非常挑剔(例如,用户可以输入货币符号吗?如果用户没有输入货币符号会怎样?是否允许空值?等) 上面的示例提供合理的用户体验和(相对)易于编程的解决方案之间的折衷.对于实际的生产级应用程序,您可能希望稍微调整逻辑和行为以适合您的特定应用程序.

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

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

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

Hi I am trying to read a the numbers from a text field that shows a price e.g. £3.00, and convert the value of the price to a double. Is there a way to do

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

But it won't let me do that because of the £ sign. Is there a way to strip the pound sign then read the digits.

Thanks

解决方案

There is some TextFormatter and change filter handling logic built into the JavaFX TextField API, you could make use of that.

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();
    }

}

The exact rules for DecimalFormat and the filter could get a little tricky if you are very particular about user experience (e.g. can the user enter the currency symbol? what happens if the user does not enter a currency symbol? are empty values permitted? etc.) The above example offers a compromise between a reasonable user experience and a (relatively) easy to program solution. For an actual production level application, you might wish to tweak the logic and behavior a bit more to fit your particular application.

Note, the apply button doesn't actually need to do anything to apply the change. Changes are applied when the user changes focus away from the text field (as long as they pass the change filter). So if the user clicks on the apply button, it gains, focus, the text field loses focus and the change is applied if applicable.

The above example treats the currency values as doubles (to match with the question), but those serious about currency may wish to look to BigDecimal.

For a simpler solution using similar concepts, see also:

这篇关于带有数字和字母的字符串将 javafx 加倍的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆