簡體   English   中英

Swing:為什么 JFormattedTextField 在焦點丟失時添加“,”

[英]Swing: why does JFormattedTextField adds “,” on focus lost

問題在標題中。

我在我的文本字段中顯示一個 int 數字,但是當我退出該字段時它不斷添加一個“,”......任何想法為什么?

對於代碼愛好者:

onfocuslost 調用:

if(textStiffness != null){
            String s1 = textStiffness.getText();
            if(s1 != null){
                stiffness = Float.valueOf(s1.replaceAll(",", "")).intValue();
                stiffness = Math.max(0, stiffness);
            }
        }

然后:

if(textStiffness != null){
            textStiffness.setText((""+(int)stiffness).replaceAll(",", ""));

        }

我檢查了該字段中設置的文本及其正確的 10000,但隨后更改為 10,000,我不明白為什么

您仍然沒有向我們展示JFormattedTextField正在使用的NumberFormat ,這實際上是解決您的問題所必需的關鍵信息。 我只能假設您使用的是NumberFormat.getNumberInstance()作為格式化程序,如果是這樣,如果您檢查 API 的 class,您會看到對於此 ZA8CFDE6331BD59EB2AC96F8911DC4B6 . 您想將其設置為 false 以擺脫逗號。

例如,這是我的SSCCE ,它顯示了您的問題及其解決方案:

import java.awt.BorderLayout;
import java.text.NumberFormat;

import javax.swing.*;

public class FormattedFieldFun {
   private static void createAndShowUI() {
      NumberFormat numberFormatGuFalse = NumberFormat.getNumberInstance();
      numberFormatGuFalse.setGroupingUsed(false);  // ***** HERE *****
      JFormattedTextField jftFieldGuFalse = 
          new JFormattedTextField(numberFormatGuFalse);

      NumberFormat numberFormatGuTrue = NumberFormat.getNumberInstance();
      // numberFormatGuFalse.setGroupingUsed(true); // not necessary as is default
      JFormattedTextField jftFieldGuTrue = 
          new JFormattedTextField(numberFormatGuTrue);

      JPanel panel = new JPanel(new BorderLayout());
      panel.add(jftFieldGuFalse, BorderLayout.NORTH);
      panel.add(jftFieldGuTrue, BorderLayout.SOUTH);

      JFrame frame = new JFrame("FormattedFieldFun");
      frame.getContentPane().add(panel);
      frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
      frame.pack();
      frame.setLocationRelativeTo(null);
      frame.setVisible(true);
   }

   public static void main(String[] args) {
      java.awt.EventQueue.invokeLater(new Runnable() {
         public void run() {
            createAndShowUI();
         }
      });
   }
}

閱讀文檔,我發現了一些觀察結果:

注意:一些格式化程序可能會不斷更新該值,使失去焦點變得毫無意義,因為該值始終與文本指定的值相同。

請注意,盡管 JFormattedTextField class 從 JTextField class 繼承了 setText 方法,但您通常不會在格式化的文本字段上調用 setText 方法。 如果這樣做,字段的顯示會相應更改,但值不會更新(除非字段的格式化程序不斷更新它)。

還有setFocusLostBehavior(int)

指定字段失去焦點的結果。 可能的值在 JFormattedTextField 中定義為 COMMIT_OR_REVERT(默認值)、COMMIT(如果有效則提交,否則保持不變)、PERSIST(什么都不做)和 REVERT(更改文本以反映值)。

暫無
暫無

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

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