首页javajtextareaJava Swing - 如何在JTextArea之间复制文本

Java Swing - 如何在JTextArea之间复制文本

我们想知道如何在JTextArea之间复制文本。
import java.awt.BorderLayout;

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);
  }
}