Reading the Robot's CommandsWhen the user clicks the Go button, Java will call the actionPerformed method in the RobotProject class. That method is where all the excitement happens in this project. Everything starts by removing the Robot from the screen, which is done simply by calling the setVisible method of JFrame with a value of false: public void actionPerformed(ActionEvent e) { try{ setVisible(false); . . . } When the Robot disappears from the screen, the program the user wants to control regains the focus, so all the Robot has to do is to send keystrokes and mouse events to it. All that's done with a Java Robot object, and you can see the methods of the Robot class in Table 7.6.
To perform its magic, the Robot project uses a Java Robot object named robot, and everything starts by creating that object and making it pause for half a second while the Robot project's window disappears from the screen: public void actionPerformed(ActionEvent e) { try{ setVisible(false); Robot robot = new Robot(); robot.delay(500); . . . } The Robot has to parse the commands given it by the user, whether they come from a file or the text area. In either case, there is only one command to a line. If the user specified a filename for the Robot to read commands from, the commands are read in from that file with a BufferedReader object, which reads text line by line: public void actionPerformed(ActionEvent e) { try{ setVisible(false); Robot robot = new Robot(); robot.delay(500); if (!jFileName.getText().equals("")){ BufferedReader bufferedFile = new BufferedReader( new FileReader(jFileName.getText())); int commandIndex = 0; String inline = ""; while((inline = bufferedFile.readLine()) != null){ commands[commandIndex++] = inline; } numberCommands = commandIndex; } . . . This stores the number of commands in an int variable named numberCommands and the actual commands in a String array named commands. For example, if the control file contained the text t:abc t:xyz in two lines, then commands[0] would hold "t:abc" and commands[1] would hold "t:xyz". Alternatively, if the user entered his commands in the text area that appears in Figure 7.1, you can read the text there and split it on newline characters to fill numberCommands and commands: public void actionPerformed(ActionEvent e) { try{ setVisible(false); Robot robot = new Robot(); robot.delay(500); if (!jFileName.getText().equals("")){ BufferedReader bufferedFile = new BufferedReader( new FileReader(jFileName.getText())); int commandIndex = 0; String inline = ""; while((inline = bufferedFile.readLine()) != null){ commands[commandIndex++] = inline; } numberCommands = commandIndex; } else { commands = jTextArea.getText().split("\n"); numberCommands = commands.length; } . . . |