Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> Java

Cách vô hiệu hóa cut, copy, paste trong JTextArea trong Java

JTextArea là lớp con của JTextComponent và là thành phần văn bản nhiều dòng để hiển thị hoặc cho nhập văn bản. JTextArea tạo CaretListener khi triển khai chức năng. Mặc định, JTextArea hỗ trợ cut, copy, paste, chúng ta có thể vô hiệu hóa/tắt chức năng này bằng getInputMap().put() của JTextArea. Dùng KeyStroke.getKeyStroke("control X") cho cut, KeyStroke.getKeyStroke("control C") cho copy, KeyStroke.getKeyStroke("control V") cho paste.

Ví dụ

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"); // Vô hiệu hóa 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"); // Vô hiệu hóa 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"); // Vô hiệu hóa 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();
    }
}

Kết quả

Cách vô hiệu hóa cut, copy, paste trong JTextArea trong Java