JTextField: focus next component when textfield is full / autoskip / Auto-Tabbing
I want to implement autoskip with JTextField, but don't know what is the best way to do this.
What is autoskip/Auto-Tabbing? When you reach the defined length limit of a textfield, you are automatically taken to the next field. (like pressing Tab, focus next component) Or what name do you use for this behaviour?
I tried this:
JTextField.getDocument.addChangeListener()
: compare length and caret position.
seems usable, but I can't distinguish typed user input from calls to JTextField.setText(String)
.
Focus should not be changed when text is changed by gui-refresh.
What开发者_运维知识库 do you think is the best way to implement this?
Perhaps you want to add a KeyListener
to the component instead. You can still check the length and caret position, but it will only fire when a key is pressed/typed.
Your code may look similar to the following:
addKeyListener(new KeyAdapter(){
public void keyTyped(KeyEvent e) {
if (getText().length() >= MAX_LENGTH) {
// Move the focus
}
}
});
Edit in response to comment:
I might suggest using @camickr's suggestion:
private DocumentListener myTabChangeListener;
@Override
public void setText(String text) {
getDocument().removeDocumentListener(myTabChangeListener);
super.setText(text);
getDocument().addDocumentListener(myTabChangeListener);
}
See Text Field Auto Tab.
Focus should not be changed when text is changed by gui-refresh.
a) removeListener
b) setText
c) addListener
Edit:
If you don't really like the concept of of needing the ChainDocumentFilter, then get rid of all references to that class. You can replace the provideErrorFeedback() method call with a Toolkit.beep() if you want.
In your listener create a flag isAPI to distinguish whether it's your code calls setText(). Set the flag to true before setText() call and reset it back after.
When it's true do nothing and move focus in opposite case.
精彩评论