Retrieve the focus at the beginning of the TextField if it loses it in Java

0

Problem photo:

Question:

If the user clicks once, the focus is automatically placed at the beginning of the TextField, but you can click anywhere in the TextField and it lets you write. How can I make the focus always placed at the beginning of the TextField?

    
asked by Robert Gomez 19.11.2016 в 02:16
source

1 answer

1

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());
        }
    });
    
answered by 19.11.2016 / 02:35
source