Cut, paste, and copy in a JTextField in Java

Description

The following code shows how to cut, paste, and copy in a JTextField.

Example


      //from   ww w .  j  av a  2s .  c o  m

import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JTextField;
import javax.swing.event.CaretEvent;
import javax.swing.event.CaretListener;

public class Main {
  public static void main(String args[]) {
    final JTextField textField = new JTextField(15);
    JButton buttonCut = new JButton("Cut");
    JButton buttonPaste = new JButton("Paste");
    JButton buttonCopy = new JButton("Copy");

    JFrame jfrm = new JFrame("Cut, Copy, and Paste");
    jfrm.setLayout(new FlowLayout());
    jfrm.setSize(230, 150);
    jfrm.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

    buttonCut.addActionListener(new ActionListener() {
      public void actionPerformed(ActionEvent le) {
        textField.cut();
      }
    });

    buttonPaste.addActionListener(new ActionListener() {
      public void actionPerformed(ActionEvent le) {
        textField.paste();
      }
    });

    buttonCopy.addActionListener(new ActionListener() {
      public void actionPerformed(ActionEvent le) {
        textField.copy();
      }
    });

    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: ");
      }
    });

    jfrm.add(textField);
    jfrm.add(buttonCut);
    jfrm.add(buttonPaste);
    jfrm.add(buttonCopy);
    jfrm.setVisible(true);
  }
}

The code above generates the following result.

Cut, paste, and copy in a JTextField in Java




















Home »
  Java Tutorial »
    Swing »




Action
Border
Color Chooser
Drag and Drop
Event
Font Chooser
JButton
JCheckBox
JComboBox
JDialog
JEditorPane
JFileChooser
JFormattedText
JFrame
JLabel
JList
JOptionPane
JPasswordField
JProgressBar
JRadioButton
JScrollBar
JScrollPane
JSeparator
JSlider
JSpinner
JSplitPane
JTabbedPane
JTable
JTextArea
JTextField
JTextPane
JToggleButton
JToolTip
JTree
Layout
Menu
Timer