我有一个 JFormattedTextField
,它以以下格式屏蔽电话号码:
(###) ###-####
我需要检索未格式化的原始##########
以存储在数据库中。
目前,我正在使用 .getText().replaceAll("\\)", "").replaceAll("\\(", "").replaceAll("-", "").replaceAll("", "")
,但这看起来应该更容易。
有没有办法从 JFormattedTextField
获取未屏蔽、未格式化的原始输入?
这是MVCE举例说明:
public static void main(String args[]) {
final JFormattedTextField phone = new JFormattedTextField();
try {
phone.setFormatterFactory(new javax.swing.text.DefaultFormatterFactory(new javax.swing.text.MaskFormatter("(###) ###-####")));
} catch(ParseException e) {
e.printStackTrace();
}
phone.setPreferredSize(new Dimension(125, phone.getPreferredSize().height));
final JButton button = new JButton("Get Text");
button.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
System.out.println(phone.getText().replaceAll("\\)", "").replaceAll("\\(", "").replaceAll("-", "").replaceAll(" ", ""));
}
});
JFrame frame = new JFrame();
JPanel panel = new JPanel();
panel.add(phone);
panel.add(button);
frame.add(panel);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
最佳答案
为什么不使用MaskFormatter
:
maskF = new MaskFormatter("(###) ###-####");
maskF.setValueContainsLiteralCharacters ( false );
askF.setOverwriteMode ( true );
maskF.setValidCharacters ( "0123456789" );
fTextField = new JFormattedTextField(maskF);
fTextField.addPropertyChangeListener("value", this);
//...
@Override
public void propertyChange(PropertyChangeEvent e) {
Object source = e.getSource();
if (source == fTextField) {
if(fTextField.getValue() != null){
System.out.println((fTextField.getValue()));
}
}
}
输入 (123) 456-7890
并按 Enter。输出将是
1234567890
通常,由于掩码未完成,fTextField.getValue()
返回null
完整代码
public class Main implements PropertyChangeListener {
private JFormattedTextField fTextField;
private MaskFormatter maskF ;
public static void main(String args[]) throws ParseException {
new Main().init();
}
private void init() throws ParseException {
JFrame f = new JFrame();
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
Container content = f.getContentPane();
content.setLayout(new BoxLayout(content, BoxLayout.PAGE_AXIS));
maskF = new MaskFormatter("(###) ###-####");
maskF.setValueContainsLiteralCharacters ( false );
maskF.setOverwriteMode ( true );
maskF.setValidCharacters ( "0123456789" );
fTextField = new JFormattedTextField(maskF);
fTextField.addPropertyChangeListener("value", this);
content.add(fTextField );
f.setSize(300, 100);
f.setVisible(true);
}
@Override
public void propertyChange(PropertyChangeEvent e) {
Object source = e.getSource();
if (source == fTextField) {
if(fTextField.getValue() != null){
System.out.println((fTextField.getValue()));
}
}
}
}
关于java - 从 JFormattedTextField 获取原始、未格式化、未屏蔽的文本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21080007/