Frage

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);

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.

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

War es hilfreich?

Lösung

u can use another solution that i prefer

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

example:

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);
     }

    }
}

then

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

i think this is better than using jFormattedTextField

Andere Tipps

There are some problems in your assumption, make sure what you need, if you need letters and numbers, HEX is not what you need,

"H" should give me only (0-9, a-z or A-Z) but im getting it wrong.

This is wrong assumption, "H" should give you Any hex character (0-9, a-f or A-F).

See the javadoc : MaskFormatter

Also I'd suggest you to have a look at : Implementing a Document Filter

HHHH will make the output hexadecimal. Use AAAAAAA

Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top