[Solved] How to type where the users cursor is


If you need to set a text when the user selected a text field you will need to use the focusGained and focusLost events to see when the text field has been selected (gain focus), or it is deselected (lost focus).

Here is an example,

import java.awt.event.FocusEvent;
import java.awt.event.FocusListener;

import javax.swing.JTextField;

public class Main {

    public static void main(String args[]) {
        final JTextField textField = new JTextField();

        textField.addFocusListener(new FocusListener() {

            @Override
            public void focusGained(FocusEvent e) {
                // Your code here
                textField.setText("Sample Text");
            }

            @Override
            public void focusLost(FocusEvent e) {
                // Your code here
                textField.setText("");
            }
        });
    }
}

Or else you can type using Java Robot class as follows,

import java.awt.event.FocusEvent;
import java.awt.event.FocusListener;

import javax.swing.JTextField;

import java.awt.Robot; 
import java.awt.event.KeyEvent; 

public class Main {

    public static void main(String args[]) {
        // Create an instance of Robot class 
        Robot robot = new Robot();

        final JTextField textField = new JTextField();

        textField.addFocusListener(new FocusListener() {

            @Override
            public void focusGained(FocusEvent e) {
                // Your code here
                // Press keys using robot. A gap of 
                // of 500 mili seconds is added after 
                // every key press 
                robot.keyPress(KeyEvent.VK_H); 
                Thread.sleep(500); 
                robot.keyPress(KeyEvent.VK_E); 
                Thread.sleep(500); 
                robot.keyPress(KeyEvent.VK_L); 
                Thread.sleep(500); 
                robot.keyPress(KeyEvent.VK_L); 
                Thread.sleep(500); 
                robot.keyPress(KeyEvent.VK_O);
            }

            @Override
            public void focusLost(FocusEvent e) {
                // Your code here
                textField.setText("");
            }
        });
    }
}

solved How to type where the users cursor is