Search code examples
javaswingclipboardjtextarea

Copy button in Notepad program


I wonder how do I copy just the highlighted text in my notepad and not the whole of it to the clipboard.

Here's the code I wrote which copy the whole content of the JTextArea of my notepad:

private void menu_edit_copyActionPerformed(java.awt.event.ActionEvent evt) {                                               
    StringSelection stringSelection = new StringSelection(TextArea_Main.getText());
    Clipboard clpbrd = Toolkit.getDefaultToolkit ().getSystemClipboard ();
    clpbrd.setContents (stringSelection, null);
}        

Solution

  • Use getSelectedText instead of getText