2

所以,我基本上想在文本字段中输入一个字母,然后让机器人响应并输入按键。我已经编写了这段代码,我想象它会如何工作,但它没有,而且我有点坚持想法。

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);

} 
}
4

2 回答 2

2
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(); 
    } 
于 2012-02-07T10:28:25.897 回答
2
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);
    }
}

Shift键入+时的典型输出w Enter

Action on W
Pressing key
Press any key to continue . . .
于 2012-02-07T10:36:15.287 回答