2

Type in the Notepad using Java

 2 years ago
source link: https://dev.to/satvik/type-in-the-notepad-using-java-4pmh
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

Type in the Notepad using Java

Let's make a java program that will open up notepad and type some text in it .

You will have to import 3 libraries which we would be using :

import java.awt.*;
import java.awt.event.KeyEvent;
import java.io.IOException;

Enter fullscreen mode

Exit fullscreen mode

Create a class and add a main method , in this program we will have to throw 3 exceptions

  1. IOException
  2. InterruptedException
  3. AWTException

We will write this line to open up notepad

Runtime.getRuntime().exec("notepad.exe");

Enter fullscreen mode

Exit fullscreen mode

We will use Thread.sleep to create a delay in out typewriter so that notepad opens up and out typewriter doesn't type anywhere else

Thread.sleep(2000);

Enter fullscreen mode

Exit fullscreen mode

Then we will use the Robot Class to create the typewriter effect

r.keyPress(KeyEvent.VK_H);

Enter fullscreen mode

Exit fullscreen mode

The line above display the letter H on the notepad .Like this we can print any letter to form words and sentences.

We can then use Thread.sleep to have a pause and create a natural typing effect

Thread.sleep(500); // 0.5 seconds

Enter fullscreen mode

Exit fullscreen mode

Thread.sleep() takes argument in milliseconds

Using this you can display multiple letters in the notepad

import java.awt.*;
import java.awt.event.KeyEvent;
import java.io.IOException;

public class notepadType{
public static void main (String[]args) throws IOException, InterruptedException, AWTException{
Runtime.getRuntime().exec("notepad.exe");

Thread.sleep(2000); // 2 seconds
Robot r=new Robot();
r.keyPress(KeyEvent.VK_H);
Thread.sleep(500);
r.keyPress(KeyEvent.VK_E);
Thread.sleep(500);
r.keyPress(KeyEvent.VK_L);
Thread.sleep(500);
r.keyPress(KeyEvent.VK_L);
Thread.sleep(500);
r.keyPress(KeyEvent.VK_O);
Thread.sleep(500);
r.keyPress(KeyEvent.VK_SPACE); // displays a whitespace
Thread.sleep(500);
r.keyPress(KeyEvent.VK_W);
Thread.sleep(500);
r.keyPress(KeyEvent.VK_O);
Thread.sleep(500);
r.keyPress(KeyEvent.VK_R);
Thread.sleep(500);
r.keyPress(KeyEvent.VK_L);
Thread.sleep(500);
r.keyPress(KeyEvent.VK_D);
// hello world 
    }
}   

Enter fullscreen mode

Exit fullscreen mode

Footnotes:


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK