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

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

问题描述

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

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

但由于£符号,它不会让我这样做。有没有办法剥去英镑符号然后读取数字。



谢谢

解决方案

有一些

  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;

类CurrencyFormatter扩展TextFormatter< Double> {
private static final double DEFAULT_VALUE = 5.00d;
private static final String CURRENCY_SYMBOL =\ u00A3; //英镑

私有静态最终DecimalFormat strictZeroDecimalFormat
=新的DecimalFormat(CURRENCY_SYMBOL +###,## 0.00);

CurrencyFormatter(){
super(
//字符串转换器在字符串和值属性之间转换。
new StringConverter< Double>(){
@Override
public String toString(Double value){
return strictZeroDecimalFormat.format(value);
}

@Override
public Double fromString(字符串字符串){
try {
return strictZeroDecimalFormat.parse(string).doubleValue();
} catch(ParseException e){
return Double.NaN;
}
}
},
DEFAULT_VALUE,
//如果无法解析,则更改过滤器拒绝文本输入。
change - > {
试试{
strictZeroDecimalFormat.parse(change.getControlNewText());
回报变化;
} catch(ParseException e){
返回null;
}
}
);
}
}

公共类FormattedTextField extends Application {

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

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

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

);

标签值=新标签();
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



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




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天全站免登陆