如何在 Java 中实现 JTextField 的剪切、复制和粘贴功能?
JTextField 是JTextComponent 类的子类,允许编辑单行文本。我们可以使用cut()、copy()和paste()方法在JTextField组件中实现剪切、复制和粘贴功能。这些是JTextFeild类中的预定义方法。
语法
public void cut() public void copy() public void paste()
示例
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(); } }
输出
广告