1

问题在标题中。

我在我的文本字段中显示一个 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,我不明白为什么

4

2 回答 2

2

您仍然没有向我们展示NumberFormat正在JFormattedTextField使用的内容,而这实际上是解决您的问题所必需的关键信息。我只能假设你使用的NumberFormat.getNumberInstance()是格式化程序,如果是这样,如果你检查这个类的 API,你会看到这个对象的 groupingUsed 属性默认设置为 true。您想将其设置为 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();
         }
      });
   }
}
于 2011-07-15T03:14:23.690 回答
1

阅读文档,我发现了一些观察结果:

注意:一些格式化程序可能会不断更新该值,使失去焦点变得毫无意义,因为该值始终与文本指定的值相同。

请注意,尽管 JFormattedTextField 类从 JTextField 类继承了 setText 方法,但您通常不会对格式化的文本字段调用 setText 方法。如果这样做,字段的显示会相应更改,但值不会更新(除非字段的格式化程序不断更新它)。

还有setFocusLostBehavior(int)

指定字段失去焦点的结果。可能的值在 JFormattedTextField 中定义为 COMMIT_OR_REVERT(默认值)、COMMIT(如果有效则提交,否则保持一切不变)、PERSIST(什么都不做)和 REVERT(更改文本以反映值)。

于 2011-07-15T00:43:09.547 回答