java.awt.Robot keyPress()方法输入错误

时间:2017-11-12 00:23:35

标签: java

我在程序中遇到错误。不是编译错误,而是程序本身执行中的错误。当调用我的type()方法时,当且仅当没有大写字母时才输入String(我尝试更改字符串)。并且输入随机字符代替字符串的字符。任何有用的见解,或只是知道我并不孤单,将不胜感激。谢谢!

import java.awt.AWTException;
import java.awt.Robot;
import javax.swing.JOptionPane;
import java.awt.event.KeyEvent;
import java.lang.Character;
import java.lang.IllegalArgumentException;
public class TicketMaker
{
    public static void main(String[] args) throws InterruptedException
    {
        Robot robot = null;
        String lottoMessage = "Vindex Lotto Ticket # ";
        JOptionPane.showMessageDialog(null,"Running program", "Ticket Master", JOptionPane.PLAIN_MESSAGE);
        Thread.sleep(4000);
        try
        {
            robot = new Robot(); 
        }
        catch(AWTException e)
        {
            String err = "Could not instantiate Robot class!";
            errprint(err);
            System.exit(-1);
        }


        try
        {
             robot.keyPress(KeyEvent.VK_E); //Open book
             Thread.sleep(2000);
             type(lottoMessage, robot);
        }
        catch(IllegalArgumentException e)
        {
            errprint("Could not begin book writing"); 
        }
    }
    public static void errprint(String m)
    {
        JOptionPane.showMessageDialog(null,"Error! " + m);
    }
    public static void type(String toType, Robot robo)
    {
         char character;
         int ascii;
         int limit = toType.length(); //11
         int i;
         for( i = 0; i < limit; i++)
         {
            character = toType.charAt(i);
            ascii = (int)character;
            robo.keyPress(ascii);
         }
     try
     {
        Thread.sleep(500);
     }
     catch(InterruptedException e)
     {
        errprint("Sleep failed!");
     }
    }
}

1 个答案:

答案 0 :(得分:1)

如果您想通过机器人发送大写字母,您必须输入班次。也适用于数字上方的任何特殊字符。机器人的工作方式就像在自己的键盘上打字一样。

robot.keyPress(KeyEvent.VK_SHIFT);

在你调用keyPress之后,调用keyRelease来模拟你的手指离开键。