I've got the problem that I've got the regex check on an input field and if the input is not as it should be and i press tab to check and normally to move to the next element, it should stay at that current field. But because of the normal tab policy it moves to the next element and even if i request focus on the current element it still moves to the next one.
Thanks for the help beforehand :)
This is my Code snippet:
}else if(comp.getName().equals("input_dauer")){
System.out.println("Test3");
final Pattern pattern = Pattern.compile("^[\\d]{0,}[,.]+[\\d]{1,3}$");
if (!pattern.matcher(input_dauer.getText()).matches()) {
lblDauer.setForeground(Color.red);
MandatoryDauer = 0;
comboBox_aktivitaet.requestFocus();
input_dauer.requestFocus();
}
else{
lblDauer.setForeground(Color.decode("#1E2F3F"));
MandatoryDauer = 1;
textArea_beschreibung.requestFocus();
}
You may disable the focus traversal keys of the JTextField
(or whatever your Component
is) with setFocusTraversalKeysEnabled(false)
, and manually transfer the focus when needed.
In the following example, if the text's length is less than 5 characters, it is deemed invalid so we don't transfer the focus.
If it is valid (length>=5), we transfer the focus with transferFocus()
if we want to stick with the logical focus order, or requestFocus()
to transfer to a particular component .
A dummy button has been added so that you can watch the focus behaviour.
JPanel contentPane = new JPanel();
JFrame fr = new JFrame();
JButton someButton = new JButton("Button");
JTextField textField = new JTextField(10);
textField.setFocusTraversalKeysEnabled(false);
textField.addKeyListener(new KeyAdapter() {
@Override
public void keyPressed(final KeyEvent ke) {
JTextField source = (JTextField) ke.getSource();
if (ke.getKeyCode() == KeyEvent.VK_TAB) {
if (source.getText().length() >= 5) {
System.out.println("Tab with valid text, transferring focus");
source.transferFocus();// or someButton.requestFocus()
} else {
System.out.println("Tab with invalid text");
}
}
}
});
contentPane.add(textField);
contentPane.add(someButton);
fr.setContentPane(contentPane);
fr.pack();
fr.setVisible(true);