如何使用仅允许使用字母和数字的JFormattedTextField [英] How to use JFormattedTextField allowing only letters and numbers

查看:293
本文介绍了如何使用仅允许使用字母和数字的JFormattedTextField的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有此代码,无法正确获取MaskFormatter
maskformatter

I have this code and cannot get MaskFormatter right
maskformatter

MaskFormatter formatter = null;
  try {
    formatter = new MaskFormatter("HHHHHHH");
  } catch (ParseException e) {
    e.printStackTrace();
  }

txtTroll = new JFormattedTextField(formatter);

我需要任何十六进制字符(0-9,a-z或A-Z),并且"H"应
只给我(0-9,a-z或A-Z),但我误会了.

I need Any hex character (0-9, a-z or A-Z) and the "H" should
give me only (0-9, a-z or A-Z) but im getting it wrong.

当我输入文字时,只输入大写字母,而且速度很慢
当我单击txtTroll时,所有字母都消失了

When i type text only capital letters are typed and it's slow to
and when i click away from the txtTroll all letters vanish

推荐答案

u可以使用我更喜欢的另一种解决方案

u can use another solution that i prefer

编写ur Document类,并使用regex expr

write ur Document class and rewrite it's insertString method using regex expr

示例:

import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.text.AttributeSet;
import javax.swing.text.PlainDocument;

/**
*
* @author cpp-qt
*/
public class HexDocument extends PlainDocument {

private String text = "";

@Override
public void insertString(int offset, String txt, AttributeSet a) {
    try {
        text = getText(0, getLength());
        if ((text + txt).matches("[0-9a-fA-F]{0,7}")) {
            super.insertString(offset, txt, a);
        }
     } catch (Exception ex) {
        Logger.getLogger(HexDocument.class.getName()).log(Level.SEVERE, null, ex);
     }

    }
}

然后

将其设置为ur textField的文档,例如this.jTextField1.setDocument(new HexDocument());

set it as ur textField's document like this this.jTextField1.setDocument(new HexDocument());

我认为这比使用jFormattedTextField更好

i think this is better than using jFormattedTextField

这篇关于如何使用仅允许使用字母和数字的JFormattedTextField的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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