Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How would I make a paste from java using the system clipboard?

Tags:

java

clipboard

I want to make a paste from the system clipboard in java. How would I do this?

like image 743
Globmont Avatar asked Apr 13 '26 16:04

Globmont


2 Answers

While the robot class would work, it's not as elegant as using the system clipboard directly, like this:

private void onPaste(){
    Clipboard c = Toolkit.getDefaultToolkit().getSystemClipboard();
    Transferable t = c.getContents(this);
    if (t == null)
        return;
    try {
        jtxtfield.setText((String) t.getTransferData(DataFlavor.stringFlavor));
    } catch (Exception e){
        e.printStackTrace();
    }//try
}//onPaste
like image 120
user85116 Avatar answered Apr 16 '26 05:04

user85116


You could use the robot class like this

try
{
    Robot r = new Robot();
    r.keyPress(KeyEvent.VK_CONTROL);
    r.keyPress(KeyEvent.VK_V);
    r.keyRelease(KeyEvent.VK_CONTROL);
    r.keyRelease(KeyEvent.VK_V);

}
catch(Exception e)
{

}
like image 29
The Java Man Avatar answered Apr 16 '26 06:04

The Java Man



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!