How can we disable cut, copy and paste functionality of a JTextArea in Java?

AWTJavaObject Oriented ProgrammingProgrammingSwing

A JTextArea is a subclass of the JTextComponent class and it is a multi-line text component to display the text or allow a user to enter the text. A JTextArea can generate a CaretListener interface when we are trying to implement the functionality of the JTextArea. By default, the JTextArea class can support cut, copy and paste functionality, we can also disable or turn off the functionality of cut, copy and paste by using the getInputMap().put() method of JTextArea class. We can use KeyStroke.getKeyStroke("control X") for cut, KeyStroke.getKeyStroke("control C") for copy and KeyStroke.getKeyStroke("control V") for paste.

Example.

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class JTextAreaCutCopyPasteDisableTest extends JFrame {
   private JTextArea textArea;
   private JButton cut, copy, paste;
   private JPanel panel;
   public JTextAreaCutCopyPasteDisableTest() {
      setTitle("JTextAreaCutCopyPasteDisable Test");
      setLayout(new BorderLayout());
      panel = new JPanel();
      textArea = new JTextArea();
      cut = new JButton("Cut");
      cut.addActionListener(new ActionListener() {
         public void actionPerformed(ActionEvent ae) {
            textArea.getInputMap().put(KeyStroke.getKeyStroke("control X"), "none");// disable cut 
         }
      });
      panel.add(cut);
      copy = new JButton("Copy");
      copy.addActionListener(new ActionListener() {
         public void actionPerformed(ActionEvent ae) {
            textArea.getInputMap().put(KeyStroke.getKeyStroke("control C"), "none"); // disable copy
         }
      });
      panel.add(copy);
      paste = new JButton("Paste");
      paste.addActionListener(new ActionListener() {
         public void actionPerformed(ActionEvent ae) {
            textArea.getInputMap().put(KeyStroke.getKeyStroke("control V"), "none"); // disable paste
         }
      });
      panel.add(paste);
      add(panel, BorderLayout.NORTH);
      add(new JScrollPane(textArea), BorderLayout.CENTER);
      setSize(400, 250);
      setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
      setLocationRelativeTo(null);
      setVisible(true);
   }
   public static void main(String []args) {
      new JTextAreaCutCopyPasteDisableTest();
   }
}

Output

raja
Published on 23-Jul-2019 16:42:10
Advertisements