Reputation: 23
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);
}
}
Upvotes: 2
Views: 2106
Reputation: 168825
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);
}
}
Action on W
Pressing key
Press any key to continue . . .
Upvotes: 2
Reputation: 2795
try
{
Robot robot = new Robot();
bookIDText = new JTextField ();
this.add(bookIDText);
String words = bookIDText.getText().toString();
if (words.equalsIgnoreCase("W"))
{
robot.keyPress(KeyEvent.VK_H);
}
}
catch (AWTException e)
{
e.printStackTrace();
}
Upvotes: 2