Search code examples
javaswingkeypressjtextfieldawtrobot

Trying to get a Robot keypress from reading a text field in Java


So, I essentially want to type in a letter into the text field and then have the Robot respond and enter a key press. I've written this code how I imagined it would work, but it doesn't and I'm kinda stuck for ideas.

package robottest;

import java.awt.AWTException; 
import java.awt.Robot; 
import java.awt.event.KeyEvent;
import javax.swing.*;
import java.awt.event.*;
import java.awt.*;

public class RobotTest extends JFrame
{
    JTextField bookIDText;

public RobotTest()
{
    try
    {
    Robot robot = new Robot(); 
    bookIDText = new JTextField ();
    this.add(bookIDText);
    String words = bookIDText.getText().toString();
    if (words == "W")
        {
            robot.keyPress(KeyEvent.VK_H);
        }
    }
    catch (AWTException e) 
    { 
        e.printStackTrace(); 
    } 
}
public static void main(String[] args) 
{ 


        RobotTest frame = new RobotTest();
        frame.pack();
        frame.setVisible(true);
        frame.setResizable( false );
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

} 
}

Solution

  • import java.awt.AWTException;
    import java.awt.Robot;
    import java.awt.event.KeyEvent;
    import javax.swing.*;
    import java.awt.event.*;
    import java.awt.*;
    
    public class RobotTest extends JFrame
    {
        JTextField bookIDText;
    
        public RobotTest() throws AWTException
        {
            final Robot robot = new Robot();
            bookIDText = new JTextField();
            this.add(bookIDText);
            bookIDText.addActionListener( new ActionListener(){
                public void actionPerformed(ActionEvent ae) {
                    String words = bookIDText.getText().toString();
                    System.out.println("Action on " + words);
                    if (words.equals("W"))
                    {
                        System.out.println("Pressing key");
                        robot.keyPress(KeyEvent.VK_H);
                    }
                }
            } );
        }
    
        public static void main(String[] args) throws Exception
        {
            RobotTest frame = new RobotTest();
            frame.pack();
            frame.setVisible(true);
            frame.setResizable( false );
            frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        }
    }
    

    Typical output on typing Shift+w Enter.

    Action on W
    Pressing key
    Press any key to continue . . .