JFormattedTextField 接受不同的位数

Posted

技术标签:

【中文标题】JFormattedTextField 接受不同的位数【英文标题】:JFormattedTextField accepting different number of digits 【发布时间】:2011-07-20 07:31:15 【问题描述】:

我需要一个限制为 3 位小数的 JTextField。经过搜索,我发现了 JFormattedTextField,看起来很棒。现在的代码是:

try

    double aux = 25.4;
    MaskFormatter mascara = new MaskFormatter("####.###");
    final JFormattedTextField areaTextoXMin = new   JFormattedTextField(mascara);
    areaTextoXMin.setValue(aux);

    catch (Exception e)

    e.printStackTrace();

但是如果 aux 不是 4 位整数和 3 位小数,则不起作用,并且 JFormattedTextField 显示为空。例如,代码可以使用 aux 为 1000.000。

其他想法?

【问题讨论】:

【参考方案1】:

尝试使用NumberFormat,例如DecimalFormat 并致电 setMinimumIntegerDigits()setMaximumIntegerDigits()

【讨论】:

【参考方案2】:
import javax.swing.*;
import javax.swing.text.*;
import java.util.regex.*;
public class MyFilter extends DocumentFilter

    public void insertString(DocumentFilter.FilterBypass fb, int offset, String text, AttributeSet attr) throws BadLocationException
    
        StringBuilder sb = new StringBuilder();
        sb.append(fb.getDocument().getText(0, fb.getDocument().getLength()));
        sb.insert(offset, text);
        if(!containsOnlyNumbers(sb.toString())) return;
        fb.insertString(offset, text, attr);
    
    public void replace(DocumentFilter.FilterBypass fb, int offset, int length, String text, AttributeSet attr) throws BadLocationException
    
        StringBuilder sb = new StringBuilder();
        sb.append(fb.getDocument().getText(0, fb.getDocument().getLength()));
        sb.replace(offset, offset + length, text);
        if(!containsOnlyNumbers(sb.toString())) return;
        fb.replace(offset, length, text, attr);
    
    public boolean containsOnlyNumbers(String text)
    
        Pattern pattern = Pattern.compile("\\d*(\\.\\d0,3)?");
        Matcher matcher = pattern.matcher(text);
        boolean isMatch = matcher.matches();
        return isMatch;
    

然后你可以像这样使用它:

JTextField txt = new TextField();
DocumentFilter onlyNumberFilter = new MyFilter();
((AbstractDocument)txt.getDocument()).setDocumentFilter(onlyNumberFilter);

【讨论】:

看起来聪明实用!但是我在未定义的adjustLabel(字符串)中遇到错误。怎么解决? @Roman Rdgz 哎呀,这取自我的上一个项目。固定:)【参考方案3】:

也许有非常简单的解决方案,让小数位到无穷大,限制 以视图为例

import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.event.ActionEvent;
import java.math.RoundingMode;
import java.text.NumberFormat;
import java.util.Locale;
import javax.swing.*;

public class CurrencyFormaterTest 

    private JLabel jl;
    private JFormattedTextField jft, jft1, jft2, jft3, jft4;
    private JButton jb = new JButton("but");

    public CurrencyFormaterTest() 
        JFrame frame = new JFrame("Text Test");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        jl = new JLabel("Try with formatted text field   ");
        Locale local1 = new Locale("en", "US");
        int minFra = 0;
        int maxFra = 3;
        jft = setFormat(jft, local1, minFra, maxFra);
        //jft.setColumns(20);
        jft.setMaximumSize(new Dimension(100, 20));
        jft.setMinimumSize(new Dimension(100, 20));
        jft.setPreferredSize(new Dimension(100, 20));
        local1 = new Locale("gb", "GB");
        minFra = 2;
        maxFra = 2;
        jft1 = setFormat(jft1, local1, minFra, maxFra);
        //jft1.setColumns(20);
        jft1.setMaximumSize(new Dimension(100, 20));
        jft1.setMinimumSize(new Dimension(100, 20));
        jft1.setPreferredSize(new Dimension(100, 20));
        local1 = new Locale("de", "DE");
        minFra = 0;
        maxFra = 3;
        jft2 = setFormat(jft2, local1, minFra, maxFra);
        //jft2.setColumns(20);
        jft2.setMaximumSize(new Dimension(100, 20));
        jft2.setMinimumSize(new Dimension(100, 20));
        jft2.setPreferredSize(new Dimension(100, 20));
        local1 = new Locale("jp", "JP");
        minFra = 0;
        maxFra = 0;
        jft3 = setFormat(jft3, local1, minFra, maxFra);
        //jft3.setColumns(20);
        jft3.setMaximumSize(new Dimension(100, 20));
        jft3.setMinimumSize(new Dimension(100, 20));
        jft3.setPreferredSize(new Dimension(100, 20));
        local1 = new Locale("hk", "HK");
        minFra = 0;
        maxFra = 3;
        jft4 = setFormat(jft4, local1, minFra, maxFra);
        //jft4.setColumns(20);
        jft4.setMaximumSize(new Dimension(100, 20));
        jft4.setMinimumSize(new Dimension(100, 20));
        jft4.setPreferredSize(new Dimension(100, 20));
        frame.add(jb);
        //
        frame.add(jl);
        frame.add(jft, BorderLayout.NORTH);
        frame.add(jft1, BorderLayout.SOUTH);
        frame.add(jft2, BorderLayout.WEST);
        frame.add(jft3, BorderLayout.EAST);
        frame.add(jft4, BorderLayout.CENTER);
        jb.addActionListener(new java.awt.event.ActionListener() 

            @Override
            public void actionPerformed(ActionEvent e) 
                JOptionPane.showMessageDialog(jb, "nel text Box : " + jft.getText());
            
        );

        frame.pack();
        frame.setVisible(true);
    

    public static void main(String[] args) 
        CurrencyFormaterTest textTest = new CurrencyFormaterTest();
    

    private JFormattedTextField setFormat(JFormattedTextField jft, Locale local1, int minFra, int maxFra) 
        NumberFormat numberFormat;
        Locale local = local1;
        int setMin = minFra;
        int setMax = maxFra;
        numberFormat = NumberFormat.getCurrencyInstance(local);
        numberFormat.setMinimumFractionDigits(setMin);
        numberFormat.setMaximumFractionDigits(setMax);
        numberFormat.setRoundingMode(RoundingMode.HALF_UP);
        jft = new JFormattedTextField(numberFormat);
        jft.setValue(new Double(342.796));
        return jft;
    

【讨论】:

以上是关于JFormattedTextField 接受不同的位数的主要内容,如果未能解决你的问题,请参考以下文章

具有任意小数位数的 JFormattedTextfield

如何从 JformattedTextfield 检索货币格式值

清除 JFormattedTextField 的内容不起作用?

JFormattedTextField 仅返回默认值

获得焦点时如何选择 JFormattedTextField 中的所有文本?

为 JFormattedTextField 分配一个浮点数