Share this page 

Make JTextField unselectableTag(s): Swing


 import java.awt.*;
 import java.util.*;
 import java.awt.event.*;
 import javax.swing.*;

 class UnselectableJTextField extends JFrame {

  public UnselectableJTextField () {
    JTextField tf1,tf2;

    tf1 = new JTextField ("you can select with the mouse");
    getContentPane().add (tf1, BorderLayout.NORTH);

    tf2 = new JTextField ("you can't select with the mouse");
    // disable mouse or keyboard selection to prevent "cut and paste"
    tf2.setHighlighter(null);
    //
    getContentPane().add (tf2, BorderLayout.SOUTH);

    addWindowListener(new WindowCloser());
    }


 public static void main (String [] args) {
   Frame f = new UnselectableJTextField ();
   f.pack();
   f.setVisible(true);
   }

class WindowCloser extends WindowAdapter {
 public void windowClosing(WindowEvent e) {
   Window win = e.getWindow();
   win.setVisible(false);
   System.exit(0);
   }
 }
}