0
我想從用戶那裏得到輸入而不讓用戶按下回車鍵。 ENTER鍵在2秒後模擬,提示用戶輸入。模擬輸入密鑰java
import java.util.Timer;
import java.util.TimerTask;
import java.io.*;
public class test
{
private String str = "";
TimerTask task = new TimerTask()
{
public void run()
{
// Code for SimulateEnterKeyPress goes here
}
};
public void getInput() throws Exception
{
Timer timer = new Timer();
timer.schedule(task, 2000);
System.out.println("Input a string within 2 seconds: ");
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
str = in.readLine();
timer.cancel();
System.out.println("You have entered: "+ str);
}
public static void main(String[] args)
{
try
{
(new test()).getInput();
}
catch(Exception e)
{
System.out.println(e);
}
}
}
如何模擬在Java中ENTER按鍵?
P.S.有沒有其他簡單的替代方法可能。
你可以使用'java.awt.Robot'作爲這個'robot.keyPress(KeyEvent.VK_ENTER);' – XtremeBaumer
我只是想知道'Robot'類不會打擾哪個應用程序或者如果應用程序處於活動狀態,如果您執行該應用程序,它將按下「Enter」鍵。 – SomeJavaGuy
謝謝。我剛剛瀏覽了有關Robot類的Oracle文檔。這非常有幫助。 – 8hantanu