在 Java 中使用 MaskFormatter 将值设置为 Jformattedtextfield [英] set Value to Jformattedtextfield using MaskFormatter in java

查看:22
本文介绍了在 Java 中使用 MaskFormatter 将值设置为 Jformattedtextfield的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个 MaskFormatter 和 Jformattedtextfield .代码是

I have a MaskFormatter and Jformattedtextfield .The code for that is

try {
    mk = new MaskFormatter("**-**-**-**-**-**-**-**-**-**-**-**-**-**-**");
    mk.setPlaceholderCharacter('_');
} catch(ParseException e) {
    e.printStackTrace();
}

format1=new JFormattedTextField(mk);
format1.setBounds(170, 80, 280,25);
format1.setFont(new Font("serif",Font.PLAIN,13));
commandpanel.add(format1);

我已将 maskformatter 添加到 jformattedTextfield.单击按钮时,我试图将值设置为 format1,但 format1 字段中未显示任何内容.

I have added maskformatter to jformattedTextfield.On click of a button i am trying to set a value to format1 but nothing is getting displayed in format1 field.

这是设置值的代码

// value may be 1E0234
String value=hashmap1.get("Command 1").substring(hashmap1.get("Command 1").lastIndexOf("-")+2, hashmap1.get("Command 1").length());

format1.setValue(value);

我也尝试过使用 format1.setText(value),在这种情况下它显示在字段中但没有掩码格式器.

I also tried with format1.setText(value),in this case it is displaying in the field but without a maskformatter.

如何与掩码一起显示值.

How do i display the value along with the mask.

推荐答案

这对我有用:

public class MyJFrame extends JFrame {

MyJFrame() {
    try {
        MaskFormatter mk = null;
        try {
            mk = new MaskFormatter("**-**-**-**-**-**-**-**-**-**-**-**-**-**-**");
            mk.setPlaceholderCharacter('_');
        } catch (ParseException e) {
            e.printStackTrace();
        }
        JFormattedTextField format1 = new JFormattedTextField(mk);
        format1.setBounds(170, 80, 280, 25);
        format1.setFont(new Font("serif", Font.PLAIN, 13));
        String value = "ZZ-99-ZZ-99-ZZ-99-ZZ-99-ZZ-99-ZZ-99-ZZ-99-ZZ";//hashmap1.get("Command 1").substring(hashmap1.get("Command 1").lastIndexOf("-")+2, hashmap1.get("Command 1").length());
        String display = mk.valueToString(value);
        System.out.println("display = " + display);
        format1.setValue(value);
        add(format1);
        pack();
    } catch (ParseException ex) {
        Logger.getLogger(MyJFrame.class.getName()).log(Level.SEVERE, null, ex);
    }
}

/**
 * @param args the command line arguments
 */
public static void main(String args[]) {
    /* Create and display the form */
    java.awt.EventQueue.invokeLater(new Runnable() {
        public void run() {
            new MyJFrame().setVisible(true);
        }
    });
}
}

如果值为zz-99"则显示

If value is "zz-99" it displays

zz-99-__-__-__-__-__-__-__-__-__-__-__-__-__

这篇关于在 Java 中使用 MaskFormatter 将值设置为 Jformattedtextfield的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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