Java JTextArea set text

Description

Java JTextArea set text

// Copying selected text from one textarea to another. 
import javax.swing.Box;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;

public class Main extends JFrame {
  String demo = "line 1\n" + "line 2 \n" + "line 3\nline 4\n";

  private final JTextArea textArea1 = new JTextArea(demo, 10, 15);
  private final JTextArea textArea2 = new JTextArea(10, 15);
  private final JButton copyJButton = new JButton("Copy");

  // no-argument constructor
  public Main() {
    super("TextArea Demo");
    Box box = Box.createHorizontalBox(); // create box

    box.add(new JScrollPane(textArea1)); // add scrollpane

    box.add(copyJButton); // add copy button to box
    copyJButton.addActionListener(e->{
        textArea2.setText(textArea1.getSelectedText());
    });/*from   w  w  w  . j  av  a2 s . co  m*/

    textArea2.setEditable(false);
    box.add(new JScrollPane(textArea2)); // add scrollpane
    add(box); // add box to frame
  }

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



PreviousNext

Related