JSpinner和double用点或逗号作为分隔符

时间:2015-06-15 22:08:14

标签: java double locale separator jspinner

我想允许“逗号”和“点”两者作为分隔符。

我可以在string中使用replace方法只获取一个分隔符,但问题是double值是JSpinner的值,我无法找到任何允许两个分隔符的方法。如果我将语言环境设置为例如法语只允许一个分隔符。

1 个答案:

答案 0 :(得分:0)

只需对JFormattedTextField的{​​{1}}的{​​{1}}使用自定义格式器,就像下面的代码一样:

DefaultEditor

注意:属性JSpinner可以省略。它只是为了维护用户最后输入的状态而存在。例如,如果用户使用逗号而不是点输入值,则微调器将继续使用逗号进行旋转。点也一样。无论用户类型如何,都将保留其将来的值,当然,他/她随时可以再次对其进行更改。但是,即使没有此属性,您的问题也可以得到满足:每次将import java.text.ParseException; import javax.swing.JFormattedTextField; import javax.swing.JFormattedTextField.AbstractFormatter; import javax.swing.JFormattedTextField.AbstractFormatterFactory; import javax.swing.JFrame; import javax.swing.JSpinner; import javax.swing.JSpinner.DefaultEditor; import javax.swing.SpinnerNumberModel; public class Main { public static class CommmaDotFormatter extends AbstractFormatter { private boolean useComma = false; @Override public Object stringToValue(String text) throws ParseException { if (text == null || text.trim().isEmpty()) throw new ParseException("Null or empty text.", 0); try { useComma = (text.contains(",") && (text.indexOf(',') == text.lastIndexOf(','))); return Double.valueOf(useComma? text.replace(',', '.'): text); } catch (final NumberFormatException nfx) { //Find the location of the error (so as to generate appropriate ParseException): int i = 0; for (final int cp: text.codePoints().toArray()) { if (!Character.isDigit(cp) && cp != ',' && cp != '.') throw new ParseException("Failed to parse text \"" + text + "\".", i); ++i; } //Could happen if the text is composed by digits and more than one dot/comma: throw new ParseException("Failed to parse text \"" + text + "\".", 0); } } @Override public String valueToString(final Object value) throws ParseException { final String text = String.format("%.2f", value); return useComma? text: text.replace(',', '.'); } } public static class CommmaDotFormatterFactory extends AbstractFormatterFactory { @Override public AbstractFormatter getFormatter(final JFormattedTextField tf) { if (!(tf.getFormatter() instanceof CommmaDotFormatter)) return new CommmaDotFormatter(); return tf.getFormatter(); } } public static void main(final String[] args) { final JSpinner spin = new JSpinner(new SpinnerNumberModel(0, -10, 10, 0.01)); ((DefaultEditor) spin.getEditor()).getTextField().setFormatterFactory(new CommmaDotFormatterFactory()); final JFrame frame = new JFrame("JSpinner infinite value"); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.getContentPane().add(spin); frame.pack(); frame.setLocationRelativeTo(null); frame.setVisible(true); } } 中的给定文本解析为useComma时,只需执行text.replace(',', '.')