In this blog, I am going to explain about "How to set a string to clipboard data using java?". We will learn the automated way of copy-paste concept in this blog and later in future you can use this in any program.
Below is the example Java program to set a string to clipboard data and paste same in Notepad file.
Read more about HOW TO OPEN EXECUTABLE (.EXE) APPLICATION USING JAVA?
Read more about WHAT IS ROBOT CLASS IN JAVA?
Read more about WHAT IS TOOLKIT CLASS IN JAVA?
Below is the example Java program to set a string to clipboard data and paste same in Notepad file.
Read more about HOW TO OPEN EXECUTABLE (.EXE) APPLICATION USING JAVA?
Read more about WHAT IS ROBOT CLASS IN JAVA?
Read more about WHAT IS TOOLKIT CLASS IN JAVA?
Java Source code:
package com.helloselenium.selenium.test; import java.awt.AWTException; import java.awt.Robot; import java.awt.Toolkit; import java.awt.datatransfer.StringSelection; import java.awt.event.KeyEvent; import java.io.IOException; public class CopyPaste{ String string = "Hello Selenium"; StringSelection stringSelection = new StringSelection(string); Toolkit.getDefaultToolkit().getSystemClipboard() .setContents(stringSelection, null); try { Runtime runtime = Runtime.getRuntime(); runtime.exec("C:\\Windows\\System32\\Notepad.exe"); Robot robot = new Robot(); robot.keyPress(KeyEvent.VK_CONTROL); robot.keyPress(KeyEvent.VK_V); robot.keyRelease(KeyEvent.VK_V); robot.keyRelease(KeyEvent.VK_CONTROL); } catch (AWTException e) { e.printStackTrace(); } catch (IOException e1) { e1.printStackTrace(); } }
Below are the line by line code explanation for above Java program:
package com.helloselenium.selenium.test;
Following code is the required packages to handle Java AWTException.
import java.awt.AWTException;
import java.awt.Robot;
import java.awt.Toolkit;
import java.awt.datatransfer.StringSelection;
import java.awt.event.KeyEvent;
import java.io.IOException;
String string = "Hello Selenium";
StringSelection stringSelection = new StringSelection(string);
Toolkit.getDefaultToolkit().getSystemClipboard().setContents(stringSelection, null);
Runtime runtime = Runtime.getRuntime();
runtime.exec("C:\\Windows\\System32\\Notepad.exe");
Robot robot = new Robot();
robot.keyPress(KeyEvent.VK_CONTROL);
robot.keyPress(KeyEvent.VK_V);
robot.keyRelease(KeyEvent.VK_V);
robot.keyRelease(KeyEvent.VK_CONTROL);
0 Comments
What would you like to add in my list? I look forward to reading your comments below.