My barcode include "1039723170303CC15-78"
The reason I used DocumentFilter is I want to limit the number as 7 digit only.
And the rest of the number goes to 2nd textField automatically.
My code only working set 7 digit only and not all the rest of the number goes to next textfield. (i.e, "1039723" go 1st textField and "70303CC15-78" go 2nd textFiled. "1" is missing in the 2nd textFiled.
How can i solve this?
lblTest = new JLabel("Testing : ");
panel.add(lblText, "cell 0 1,alignx trailing");
txtTest = new JTextField(7);
AbstractDocument d = (AbstractDocument) txtTest.getDocument();
d.setDocumentFilter(new DocumentFilter() {
@Override
public void insertString(DocumentFilter.FilterBypass fb, int offset, String string, AttributeSet attr) throws BadLocationException
{
if(fb.getDocument().getLength()+string.length()>7)
{
return;
}
fb.insertString(offset, string, attr);
}
@Override
public void remove(DocumentFilter.FilterBypass fb, int offset, int length) throws BadLocationException
{
fb.remove(offset, length);
}
@Override
public void replace(DocumentFilter.FilterBypass fb, int offset, int length, String text, AttributeSet attrs)throws BadLocationException
{
if(fb.getDocument().getLength()+text.length()>7)
{
txtTest.transferFocus();
System.out.println("print.." +txtTest.getText());
return;
}
fb.insertString(offset, text, attrs);
}
});
print out put:
print Mo No.:1039723
print Mo No.:1039723
print Mo No.:1039723
The basic problem you have, is the
textyou're checking is been discard and never applied to anything.For example, if the text been entered is (assuming one character at a time)
123456789, then8will be ignored, as9will be send to the other field.What you need to do, is manually set the text of the next field with the text you are going to ignore.
Now, your current has a two fundamental flaws.
replaceshould remove any selected charactersThis example attempts to answer all of those questions
What this really needs is a delegate model, where by instead of the
DocumentFilterchanging field focus, it delegates that responsibility to some other observer, passing it the overflow textUpdate
Okay, so this is an updated version which provides three ways that the text can be set:
setTextRobotThis provides the best possible example of how a barcode scanner "might" work