Java Swing How to - Cut, paste, and copy in a JTextField








Question

We would like to know how to cut, paste, and copy in a JTextField.

Answer

//from   www  .j  a  va2s . com
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JTextField;
import javax.swing.event.CaretEvent;
import javax.swing.event.CaretListener;

public class Main {
  public static void main(String args[]) {
    final JTextField textField = new JTextField(15);
    JButton buttonCut = new JButton("Cut");
    JButton buttonPaste = new JButton("Paste");
    JButton buttonCopy = new JButton("Copy");

    JFrame jfrm = new JFrame("Cut, Copy, and Paste");
    jfrm.setLayout(new FlowLayout());
    jfrm.setSize(230, 150);
    jfrm.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

    buttonCut.addActionListener(new ActionListener() {
      public void actionPerformed(ActionEvent le) {
        textField.cut();
      }
    });

    buttonPaste.addActionListener(new ActionListener() {
      public void actionPerformed(ActionEvent le) {
        textField.paste();
      }
    });

    buttonCopy.addActionListener(new ActionListener() {
      public void actionPerformed(ActionEvent le) {
        textField.copy();
      }
    });

    textField.addCaretListener(new CaretListener() {
      public void caretUpdate(CaretEvent ce) {
        System.out.println("All text: " + textField.getText());
        if (textField.getSelectedText() != null)
          System.out.println("Selected text: " + textField.getSelectedText());
        else
          System.out.println("Selected text: ");
      }
    });

    jfrm.add(textField);
    jfrm.add(buttonCut);
    jfrm.add(buttonPaste);
    jfrm.add(buttonCopy);
    jfrm.setVisible(true);
  }
}