繁体   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