Java Swing How to - Copy text between JTextArea








Question

We would like to know how to copy text between JTextArea.

Answer

import java.awt.BorderLayout;
//  www  .j  a va  2 s.  c o  m
import javax.swing.BoxLayout;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;

public class Main {
  JFrame testFrame = new JFrame();
  JTextArea firstTextArea, secondTextArea;
  JButton copyTextButton;

  public Main() {
    JPanel textPanel = new JPanel();
    textPanel.setLayout(new BoxLayout(textPanel, BoxLayout.PAGE_AXIS));

    firstTextArea = new JTextArea(10, 50);
    secondTextArea = new JTextArea(10, 50);

    textPanel.add(new JScrollPane(firstTextArea));
    textPanel.add(new JScrollPane(secondTextArea));

    testFrame.add(textPanel, BorderLayout.CENTER);

    copyTextButton = new JButton("Copy text");
    copyTextButton.addActionListener(e ->copyText());
    testFrame.add(copyTextButton, BorderLayout.SOUTH);
  }
  public JFrame getFrame() {
    return testFrame;
  }
  private void copyText() {
    secondTextArea.setText(firstTextArea.getText());
  }
  public static void main(String[] args) {
    JFrame frame = new Main().getFrame();
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.pack();
    frame.setVisible(true);
  }
}