繁体   English   中英

JSpinner 和双点或逗号作为分隔符

[英]JSpinner and double with dot or comma as separator

我想同时允许“逗号”和“点”作为双精度分隔符。

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

只需为JSpinnerDefaultEditorJFormattedTextField使用自定义格式化程序,如下面的代码:

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(',', '.')您只需执行text.replace(',', '.')

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM