问题
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
回答1:
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
回答2:
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
回答3:
HHHH will make the output hexadecimal. Use AAAAAAA
来源:https://stackoverflow.com/questions/8203378/how-to-use-jformattedtextfield-allowing-only-letters-and-numbers