2011-12-22 23 views
0

我有许多带有数字数据的JFormattedTextdield。我已经使用了DecimalFormat,InternationalFormatter,DocumentListener,并且还使用CaretPositionListener进行了尝试。Java:JFormattedTextField更改setGroupingUsed()on focusLost&focusGained

我面对的唯一问题就是当号码输入增长和分组字符进入之间时的插入位置。

如何动态设置onGocusLost上各个jformattedtextfields的DecimalFormat的setGroupingUsed()的焦点已着色&。

任何意见或建议....

更新代码&问题: 当我尝试输入 “12345”,就加入 “1234” 逗号出现的 “1,234”。这使3 &后4之间,而不是4的格式代码,我用它来插入记号:

DecimalFormat numberFormat = (DecimalFormat) DecimalFormat.getNumberInstance(); 
    numberFormat.setMaximumFractionDigits(2); 
    numberFormat.setMinimumFractionDigits(2); 
    numberFormat.setRoundingMode(RoundingMode.HALF_UP); 

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

    return formatter; 

这是我作为一个自定义的JFormattedTextField SOLUTION实现。你有什么更好的办法来处理分组字符,而输入值,所以只需插入位置仍然正确:

public void focusGained(FocusEvent e) { 
    if (numberFormat.isGroupingUsed()) { 
     Object o = this.getValue(); 
     numberFormat.setGroupingUsed(false); 
     formatter.setFormat(numberFormat); 
     this.setFormatterFactory(new AbstractFormatterFactoryImpl()); 
     this.setValue(o); 
     this.setText(o.toString()); 
    } 
} 

public void focusLost(FocusEvent e) { 
    try { 
     this.commitEdit(); 
    } catch (ParseException ex) { 
     //Logger.getLogger(NumberFormattedTextField.class.getName()).log(Level.SEVERE, null, ex); 
    } 
    Object o = this.getValue(); 
    //System.out.println("focusLost : getValue = " + o); 
    numberFormat.setGroupingUsed(true); 
    formatter.setFormat(numberFormat); 
    this.setFormatterFactory(new AbstractFormatterFactoryImpl()); 
    this.setValue(o); 
    this.setText(o.toString()); 
    //System.out.println("focusLost : Text Set = " + o.toString()); 
} 
+3

为了尽快提供更好的帮助,请发布[SSCCE](http://sscce.org/)。 – 2011-12-22 11:14:28

回答

0

感谢,

我通过创建,管理一切,我需要一个自定义的文本框来解决。任何改进建议。问题上面添加了代码。

+0

每一个更好的AutoCompleted JComboBox/JtexField已经实现了set&moveCaret,那么没有关于JTextField,但关于从JComboBox中提取JTextComponent – mKorbel 2011-12-23 11:32:25

+0

@mKorbel,问题是在输入文本时。由于分组的“,”出现,所以插入符号是内部1位数字。 focusGained时将分组设置为false,并在focusLost时将其恢复为true。这帮助了我。对于你所提到的,他们有没有比我更好的解决方案? – Tvd 2011-12-23 11:56:47

+0

检查自动完成的JComboBox/JtexField,你可以放50pcs,每个记住最后一个选择卡雷,但在另一方面是太难回答你的问题,因为你谈论无级代码的高等级workaound,当然这里有一些优秀的Swing编码器,但没有代码,没有回答:-) – mKorbel 2011-12-23 12:00:53