如何在 Java 中禁用 JTextArea 的剪切、复制和粘贴功能?


JTextAreaJTextComponent 类的子类,它是一个多行文本组件,用于显示文本或允许用户输入文本。当我们尝试实现 JTextArea 的功能时,JTextArea 可以生成一个 CaretListener 接口。默认情况下,JTextArea 类可以支持剪切、复制和粘贴功能,我们还可以使用JTextArea 类的 getInputMap().put() 方法禁用或关闭 剪切、复制和粘贴功能。我们可以使用 KeyStroke.getKeyStroke(“control X”) 进行剪切、KeyStroke.getKeyStroke(“control C”) 进行复制和 KeyStroke.getKeyStroke(“control V”) 进行粘贴。

示例。

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

输出

更新日期:2020 年 2 月 10 日

666 次浏览

开启你的 职业生涯

通过完成课程获得认证

开始
广告
© . All rights reserved.