JSpinner并使用点或逗号作为分隔符进行双精度 [英] JSpinner and double with dot or comma as separator

查看:135
本文介绍了JSpinner并使用点或逗号作为分隔符进行双精度的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想同时使用逗号"和点"作为分隔符.

I would like to allow both "comma" and "dot" as separator in double.

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

I could use replace method in string to get only one separator, but problem is that double value is value of JSpinner and I was not able to find any method to allow both separators. If I set locale for example to French only one separator is allowed.

推荐答案

只需对JSpinnerDefaultEditorJFormattedTextField使用自定义格式器,就像下面的代码一样:

Just use a custom formatter for the JFormattedTextField of the DefaultEditor of the JSpinner, like the code below:

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.它只是为了维护用户最后一次输入的状态而存在.例如,如果用户使用逗号而不是点输入值,则微调器将继续使用逗号进行旋转.点也一样.无论用户类型是什么,都将保留它们以备将来使用,当然,他/她随时可以再次对其进行更改.但是,即使没有此属性,您的问题也可以得到满足:每次将stringToValue中的给定文本解析为double时,只需执行text.replace(',', '.').

Note: property useComma could be omitted. It simply exists to maintain the state of the last input of the user. For example if the user enters a value with comma rather than dot, then the spinner will keep spinning with commas. Same for dots. Whatever the user types will remain for future values, and of course it can be changed again any time by him/her. But your question can be satisfied even without this property: you would just have to do text.replace(',', '.') each time the given text in stringToValue before parsing it into a double.

这篇关于JSpinner并使用点或逗号作为分隔符进行双精度的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆