如何去除 JFormattedTextField 的掩码?

How to Remove Mask of JFormattedTextField?

我有一个由两个 RadioButton 控制的 JFormattedTextField。在其中一个 RadioButton 中,我设置了掩码,另一个我想清除掩码并正常输入。设置为正常类型后,它不会return getText() 的值,如果设置了掩码,则该值只有return。

如何解决这个问题?

private void setMask() {
    MaskFormatter formatter = null;
    try {
        txtPesquisar.setValue(null);
        if (rbNome.isSelected()) {
            //clear mask to type normally
            formatter = new MaskFormatter("****************************************");
            formatter.setPlaceholderCharacter(' ');
        } else {
            //set mask
            formatter = new MaskFormatter("###.###.###-##");
            formatter.setPlaceholderCharacter(' ');
        }
        txtPesquisar.setFormatterFactory(new DefaultFormatterFactory(formatter));
        txtPesquisar.requestFocus();
        txtPesquisar.selectAll();
    } catch (ParseException ex) {
        ex.printStackTrace();
    }
}

请务必在调用 getValue() 之前对 JFormattedTextField 调用 commitEdit()。根据 getValue() 上的 JFormattedTextField API 部分:

Returns the last valid value. Based on the editing policy of the AbstractFormatter this may not return the current value. The currently edited value can be obtained by invoking commitEdit followed by getValue. Returns:

例如:

import java.awt.event.ActionEvent;
import java.awt.event.KeyEvent;
import java.text.ParseException;

import javax.swing.*;
import javax.swing.text.DefaultFormatterFactory;
import javax.swing.text.MaskFormatter;

@SuppressWarnings("serial")
public class TestFormattedField extends JPanel {
    private JFormattedTextField txtPesquisar = new JFormattedTextField();
    private JRadioButton rbNome = new JRadioButton("None");
    private JRadioButton rbFormat = new JRadioButton("Format");

    public TestFormattedField() {
        txtPesquisar.setColumns(20);
        ButtonGroup btnGroup = new ButtonGroup();
        btnGroup.add(rbFormat);
        btnGroup.add(rbNome);

        rbNome.setSelected(true);
        rbNome.setMnemonic(KeyEvent.VK_N);
        rbFormat.setMnemonic(KeyEvent.VK_F);
        add(txtPesquisar);
        add(rbFormat);
        add(rbNome);
        setMask();

        add(new JButton(new SetFormatAction()));
        add(new JButton(new GetTextAction()));
    }

    private void setMask() {
        MaskFormatter formatter = null;
        try {
            txtPesquisar.setValue(null);
            if (rbNome.isSelected()) {
                //clear mask to type normally
                formatter = new MaskFormatter("****************************************");
                formatter.setPlaceholderCharacter(' ');
            } else {
                //set mask
                formatter = new MaskFormatter("###.###.###-##");
                formatter.setPlaceholderCharacter(' ');
            }
            txtPesquisar.setFormatterFactory(new DefaultFormatterFactory(formatter));
            txtPesquisar.requestFocus();
            txtPesquisar.selectAll();
        } catch (ParseException ex) {
            ex.printStackTrace();
        }
    }

    private class SetFormatAction extends AbstractAction {
        public SetFormatAction() {
            super("Set Format");
            putValue(MNEMONIC_KEY, KeyEvent.VK_S);
        }

        @Override
        public void actionPerformed(ActionEvent e) {
            setMask();
        }
    }

    private class GetTextAction extends AbstractAction {
        public GetTextAction() {
            super("Get Text");
            putValue(MNEMONIC_KEY, KeyEvent.VK_G);
        }

        @Override
        public void actionPerformed(ActionEvent e) {
            final String text = txtPesquisar.getText();
            try {
                txtPesquisar.commitEdit();
            } catch (ParseException e1) {
                String title = "Incomplete Text Entry";
                String msg = "Text -- " + text + " is not yet complete";
                JOptionPane.showMessageDialog(TestFormattedField.this, msg, title, JOptionPane.ERROR_MESSAGE);
            }  
            Object value = txtPesquisar.getValue();

            System.out.println("text: " + text);
            System.out.println("value: " + value);
        }
    }

    private static void createAndShowGui() {
        TestFormattedField mainPanel = new TestFormattedField();

        JFrame frame = new JFrame("Test JFormattedField");
        frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
        frame.getContentPane().add(mainPanel);
        frame.pack();
        frame.setLocationByPlatform(true);
        frame.setVisible(true);
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(() -> createAndShowGui());
    }
}

以后,请考虑花一点时间来创建 post minimal example program or SSCCE 因为这是让人们充分理解您的问题然后能够来帮助你。请以我的代码为例。

在 inintcomponets 之后的表单构造函数上

public Form1() {
 initComponents();
 MaskFormatter dateMask;
try {
 dateMask = new MaskFormatter("|#|#|#|#|#|#|#|#|#|#|");
 dateMask.install(JTEXTFORMATEE);
} catch (ParseException ex) {
  Logger.getLogger(Forma051.class.getName()).log(Level.SEVERE, null, ex);
}

}