Copying selected text from one textarea to another. - Java Swing

Java examples for Swing:JTextArea

Description

Copying selected text from one textarea to another.

Demo Code

import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import javax.swing.Box;
import javax.swing.JFrame;
import javax.swing.JTextArea;
import javax.swing.JButton;
import javax.swing.JScrollPane;

class TextAreaFrame extends JFrame {
  private  JTextArea textArea1 = new JTextArea(); // displays demo string
  private  JTextArea textArea2 = new JTextArea(); // highlighted text is copied here
  private final JButton copyJButton; // initiates copying of text

  // no-argument constructor
  public TextAreaFrame() {
    super("TextArea Demo");
    Box box = Box.createHorizontalBox(); // create box
    String demo = "This is a demo string to\n"
        + "illustrate copying text\nfrom one textarea to \n"
        + "another textarea using an\nexternal event\n";

    textArea1 = new JTextArea(demo, 10, 15);
    box.add(new JScrollPane(textArea1)); // add scrollpane

    copyJButton = new JButton("Copy >>>");
    box.add(copyJButton); // add copy button to box
    copyJButton.addActionListener(e -> textArea2.setText(textArea1
        .getSelectedText()));//from  ww  w.  j a v  a2s .  co m

    textArea2 = new JTextArea(10, 15);
    textArea2.setEditable(false);
    box.add(new JScrollPane(textArea2)); // add scrollpane

    add(box); // add box to frame
  }
}

public class Main {
  public static void main(String[] args) {
    TextAreaFrame textAreaFrame = new TextAreaFrame();
    textAreaFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    textAreaFrame.setSize(425, 200);
    textAreaFrame.setVisible(true);
  }
}

Related Tutorials