The method to use would be setCaretPosition (int position) to place the cursor at the beginning would be 0
MaskFormatter formatter = new MaskFormatter("(###) ###-####");
textField = new JFormattedTextField(formatter);
textField.setSize(new Dimension(100,40));
To validate this through the Focus
event we would have to add a Focuslistener to Know when that event occurs. (once the focus event is given, it can be moved to the desired place within the JFormattedTextField)
MaskFormatter formatter = new MaskFormatter("(###) ###-####");
textField = new JFormattedTextField(formatter);
textField.setSize(new Dimension(100,40));
textField.addFocusListener(new FocusListener() {
@Override
public void focusGained(FocusEvent fe) {
System.out.println("Focus In");
textField.setCaretPosition(0);
}
@Override
public void focusLost(FocusEvent fe) {
System.out.println("Focus Out");
}
});
So that always selecting the JFormattedTextField
is placed at the beginning would be with the event click
, adding a mouselistener
textField.addMouseListener(new MouseAdapter(){
public void mouseClicked(MouseEvent e){
if(textField.getText().replaceAll("[()-]", "").trim().length()==0)
textField.setCaretPosition(0);
else
textField.setCaretPosition(textField.getText().length());
}
});