Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to disable text selection on JTextArea Swing

Tags:

java

swing

I don't want the user to select the content on JTextArea. I use setEditable(false) but it's not working. How to disable this feature of JTextArea component. Could you give me advise. Thanks.

enter image description here

like image 356
Phạm Quốc Bảo Avatar asked Dec 08 '22 01:12

Phạm Quốc Bảo


2 Answers

You can set the "mark" equal to the "dot" of the caret. When these values are equal there is no text selection:

import java.awt.*;
import javax.swing.*;
import javax.swing.text.*;

public class NoTextSelectionCaret extends DefaultCaret
{
    public NoTextSelectionCaret(JTextComponent textComponent)
    {
        setBlinkRate( textComponent.getCaret().getBlinkRate() );
        textComponent.setHighlighter( null );
    }

    @Override
    public int getMark()
    {
        return getDot();
    }

    private static void createAndShowUI()
    {
        JTextField textField1 = new JTextField("No Text Selection Allowed");
        textField1.setCaret( new NoTextSelectionCaret( textField1 ) );
        textField1.setEditable(false);

        JTextField textField2 = new JTextField("Text Selection Allowed");

        JFrame frame = new JFrame("No Text Selection Caret");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.add(textField1, BorderLayout.NORTH);
        frame.add(textField2, BorderLayout.SOUTH);
        frame.pack();
        frame.setLocationByPlatform( true );
        frame.setVisible( true );
    }

    public static void main(String[] args)
    {
        EventQueue.invokeLater(new Runnable()
        {
            public void run()
            {
                createAndShowUI();
            }
        });
    }
}
like image 108
camickr Avatar answered Dec 21 '22 17:12

camickr


If you would like to just disable text selection on any swing control such as JtextArea you can use the coding below:

JtextArea.setHighlighter(null);

This one line of coding will help disable the text selection and can be placed in the constructor or within a initialized method upon Frame execution.

Hope this helps

like image 32
John Avatar answered Dec 21 '22 15:12

John