簡體   English   中英

Java:語言環境是否會影響JFormattedTextField的格式化程序

[英]Java : Does Locale affect the Formatter for JFormattedTextField

我創建了JFormattedTextField的自定義組件(NumberFormattedTextField)。 這是我使用的格式化程序:

    public static InternationalFormatter getDecimalIFormatter92() {
    // For Buy & Sale Price
    DecimalFormat numberFormat = (DecimalFormat) DecimalFormat.getNumberInstance();
    numberFormat.setMaximumFractionDigits(2);
    numberFormat.setMinimumFractionDigits(2);
    numberFormat.setRoundingMode(RoundingMode.HALF_UP);
    numberFormat.setGroupingUsed(false);

    final InternationalFormatter formatter = new InternationalFormatter(numberFormat);
    formatter.setAllowsInvalid(false);
    formatter.setMinimum(0.00);
    formatter.setMaximum(999999999.99);

    return formatter;
}

當我創建NumberFormattedTextField的實例時:

 public RelationsPanel(CashParent parent) {
    try {
    initComponents();   // startBalTxt = new NumberFormattedTextField();
    Utility.logInfo("initComponents OVER");
    myParent = parent;
    nameTxt.setSizeLimit(20);
    System.out.println("startBalTxt.setFormatter GOING FOR IT"); 
    this.startBalTxt.setFormatter(Utility.getDecimalIFormatter82());  // Must be throwing here
    System.out.println("startBalTxt.setFormatter DONE"); 
    this.currentBalTxt.setFormatter(Utility.getDecimalIFormatter82());
    } catch (Exception e) {
        Utility.logInfo("Failed to Initialize : " + e.getMessage());
        e.printStackTrace();
    }
}

NumberFormattedTextField CLASS代碼:

public class NumberFormattedTextField extends JFormattedTextField implements java.io.Serializable, DocumentListener, FocusListener {
private DecimalFormat numberFormat;
private InternationalFormatter formatter;
private double MAX_VALUE = 999999.99;
private final Map attributes = (Utility.getTextFont()).getAttributes();

/**
 * Creates a NumberFormattedTextField with 6 Integer & 2 Fractional digits.
 * Minimum is set to 0.00 and Max to 999999.99 without any grouping used.
 */
public NumberFormattedTextField() {
    super();
    createFormatter();  // Creates a default formatter, used if formatter is not set
    this.setValue(0.00);
    init();
}


private void createFormatter() {
    // Create standard DecimalFormat
    numberFormat = (DecimalFormat) DecimalFormat.getNumberInstance();
    numberFormat.setMaximumFractionDigits(2);
    numberFormat.setMinimumFractionDigits(2);
    numberFormat.setRoundingMode(RoundingMode.HALF_UP);
    numberFormat.setGroupingUsed(false);

    formatter = new InternationalFormatter(numberFormat);
    formatter.setAllowsInvalid(false);
    formatter.setMinimum(0.00);
    formatter.setMaximum(999999.99);

    this.setFormatterFactory(new AbstractFormatterFactoryImpl());
}

private void init() {
    setFont(Utility.getTextFont());
    this.getDocument().addDocumentListener(this);
    this.addFocusListener(this);
    attributes.put(TextAttribute.STRIKETHROUGH, TextAttribute.STRIKETHROUGH_ON);
    setFocusLostBehavior(PERSIST);
}

public void setFormatter(InternationalFormatter format) {
    super.setFormatter(format);
    System.out.println("Class of Format = " + format.getFormat().getClass());
    if (format.getFormat() instanceof java.text.DecimalFormat)
        numberFormat = (DecimalFormat)format.getFormat();
    else
        numberFormat = (DecimalFormat)(NumberFormat) format.getFormat();

    formatter = format;
    // AbstractFormatterFactoryImpl returns formatter straight away    
    this.setFormatterFactory(new AbstractFormatterFactoryImpl());
    calculateMaxValue();
}

private void calculateMaxValue() {
    try {
        if (formatter.getMaximum() != null) {
            //System.out.println(" MAX ALlowed = " + formatter.getMaximum());
            String no = formatter.valueToString(formatter.getMaximum());
            char seperator = java.text.DecimalFormatSymbols.getInstance().getGroupingSeparator();
            no = no.replace(String.valueOf(seperator), "");
            System.out.println("MAX Number to PArse = " + no);
            MAX_VALUE = Double.parseDouble(no);  // HERE ITS THROWING EXCEPTION
        }
    } catch (ParseException ex) {
        Logger.getLogger(NumberFormattedTextField.class.getName()).log(Level.SEVERE, null, ex);
    }
}

我的PC上的上述代碼運行良好。 但是在客戶端的PC上,它給出錯誤:無法初始化:對於輸入字符串:“ 99999999,99”錯誤/我得到的日志:

      startBalTxt.setFormatter GOING FOR IT
  INFO: initComponents OVER
  Class of Format = class java.text.DecimalFormat
  MAX Number to PArse = 99999999,99
  INFO: Failed to Initialize : For input string: "99999999,99"
  java.lang.NumberFormatException: For input string: "99999999,99"
    at sun.misc.FloatingDecimal.readJavaFormatString(FloatingDecimal.java:1241)
    at java.lang.Double.parseDouble(Double.java:540)
    at cashaccountingapp.components.NumberFormattedTextField.calculateMaxValue(NumberFormattedTextField.java:184)
 Class of Format = class java.text.DecimalFormat
    at cashaccountingapp.components.NumberFormattedTextField.setFormatter(NumberFormattedTextField.java:173)
    at cashaccountingapp.data.RelationsPanel.<init>(RelationsPanel.java:35)

我們倆的語言環境不同。

發生此錯誤的原因可能是什么? 我的NumberFormattedTextField類中有其他語言環境或其他需要注意的地方。 我希望應用程序適應系統設置並相應顯示。

如何解決這個問題?

很有可能是(不能完全確定,因為您沒有顯示初始設置並將錯誤僅破壞其消息;-)不同的語言環境是原因:一個以句點為小數點,另一個以逗號表示。 因此,如果用一個表示另一個數字的String初始化一個,則會發生沖突:逗號不解釋為小數點分隔符,因此最大值太大而無法滿足限制

得到了解決方案:

我專門得到Locale.US的DecimalFormatSymbols實例。 這有助於我使用適當的十進制分隔符以標准格式獲取字符串。 從而能夠將有效字符串解析為Double。 這是我更改的代碼,如果有幫助的話:

    private void calculateMaxValue() {
    try {
        if (formatter.getMaximum() != null) {
            String no = formatter.valueToString(formatter.getMaximum());
            // Get DecimalFormatSymbols instance of Locale.US
            char seperator = java.text.DecimalFormatSymbols.getInstance(java.util.Locale.US).getGroupingSeparator();
            no = no.replace(String.valueOf(seperator), "");
            MAX_VALUE = Double.parseDouble(no);
        }
    } catch (ParseException ex) {
        Utility.logs.log(Level.SEVERE, null, ex);
    }
}

就是這樣,不需要其他更改。

謝謝。

經過兩個小時的谷歌搜索並進行了一些更改之后,我得到了一個更簡單的解決方案,只接受點(。)作為JFormattedTextField小數點分隔符:

JFormattedTextField txtTax = new javax.swing.JFormattedTextField();
txtTax.setFormatterFactory(new DefaultFormatterFactory(new NumberFormatter(new DecimalFormat("#,##0.00", new DecimalFormatSymbols(new Locale("us", "EN"))))));

此解決方案忽略系統locale(ec,ES)並將組件設置為特定區域設置(us,EN)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM