How can we implement cut, copy and paste functionality of JTextField in Java?


A JTextField is a subclass of JTextComponent class that allows the editing of a single line of text. We can implement the functionality of cut, copy and paste in a JTextField component by using cut(), copy() and paste() methods. These are pre-defined methods in a JTextFeild class.

Syntax

public void cut()
public void copy()
public void paste()

Example

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.event.*;

public class JTextFieldCutCopyPasteTest extends JFrame {
   private JTextField textField;
   private JButton cutButton, copyButton, pasteButton;
   public JTextFieldCutCopyPasteTest() {
      setTitle("JTextField CutCopyPaste Test");
      setLayout(new FlowLayout());

      textField = new JTextField(12);
      cutButton = new JButton("Cut");
      pasteButton = new JButton("Paste");
      copyButton = new JButton("Copy");

      cutButton.addActionListener(new ActionListener() {
         public void actionPerformed(ActionEvent ae) {
            textField.cut();
         }
      });
      copyButton.addActionListener(new ActionListener() {
         public void actionPerformed(ActionEvent ae) {
            textField.copy();
         }
      });
      pasteButton.addActionListener(new ActionListener() {
         public void actionPerformed(ActionEvent le) {
            textField.paste();
         }
      });
      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: ");
         }
      });
      add(textField);
      add(cutButton);
      add(copyButton);
      add(pasteButton);

      setSize(375, 250);
      setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);setLocationRelativeTo(null);
      setVisible(true);
   }
   public static void main(String args[]) {
      new JTextFieldCutCopyPasteTest();
   }
}

Output

raja
Published on 15-Jul-2019 14:02:53
Advertisements