Reputation: 11
I wanted to create a keyboard output API type thing so that I could make a machine learning program for Tetris, and I tried:
import java.awt.*;
public class Keyboard
{
public static void main( String[] args )
{
Robot keyboard = new Robot();
keyboard.keyPress(KeyEvent.VK_A);
}
}
but it has an error for new Robot()
, it says "Unhandled exception: java.awt.AWTException". and it has an error on the line after that: "Cannot resolve symbol 'KeyEvent'", even though I have import java.awt.*;
. what am I doing wrong?
Upvotes: 1
Views: 126
Reputation: 133
let's check what errors we getting.
Unhandled exception: java.awt.AWTException
This is means you don't handle an exception thrown from calling constructor new Robot();
you need to check this in documentation here:
https://docs.oracle.com/javase/7/docs/api/java/awt/Robot.html
or use your IDE its can show which exception can be thrown.
To fix this we need to surround constructor call new Robot ();
with try-catch block
or declare an exception throw in a method main();
more about exceptions here: https://docs.oracle.com/javase/tutorial/essential/exceptions/
Cannot resolve symbol 'KeyEvent'
Its can means you missing some imports in your case you imported import java.awt.*
; but this import does not include java.awt.event
//Don't use static (*) import just import what you need in this case
//or use your IDE auto import
import java.awt.Robot;
import java.awt.event.KeyEvent;
import java.awt.AWTException;
public class MainClass {
public static void main(String[] args) {
try {
Robot rob = new Robot();
// Robot can throw an AWTException
// we need surround him with try-catch block
// Or declare exception throw in current method
// Pressing button
rob.keyPress(KeyEvent.VK_A);
// Releasing button in case if we don't do that key may stay in press state
rob.keyRelease(KeyEvent.VK_A);
} catch (AWTException e) {
// Process exception if something go wrong
e.printStackTrace();
}
}
Upvotes: 2