orange
orange

Reputation: 5405

Detecting text selection in JTextArea

I have a JTextArea and am deteching if any text is selection, if none is then two of the menu items are grayed out. The problem I have is, when I compile and open the application I have to click on the JTextArea first and then then the menu items are greyed out, if I don't they aren't even if no text is selected. I am using the following caret listener.

    textArea.addCaretListener(new CaretListener() {

        @Override
        public void caretUpdate(CaretEvent arg0) {
            int dot = arg0.getDot();
            int mark = arg0.getMark();
            if (dot == mark) {

                copy2.setEnabled(false);
                cut1.setEnabled(false);
            }
            else{
                cut1.setEnabled(true);
                copy2.setEnabled(true);
            }

        }
    });

Upvotes: 3

Views: 5256

Answers (3)

user2007397
user2007397

Reputation: 1

You can use JtextField.setHighlighter(null);

Upvotes: -1

user517491
user517491

Reputation:

You can define enable/disable logic for cut/copy menu items in a separate function, and call that function while initializing GUI, and also that function will be called on CaretUpdate (or better be MouseReleased) event.

JTextArea textArea;
......
........
public void init()
{   
    ......
    ........
    textArea=new JTextArea();
    // add textArea to parent container
    // now initialize menu items state
    setEditingMenuItemsState();
    textArea.addCaretListener(new CaretListener()
    {
        @Override
        public void caretUpdate(CaretEvent arg0)
        {
            setEditingMenuItemsState();
        }
    });
    ......
    ........
}

public void setEditingMenuItemsState()
{
    String selectedText;

    if ( textArea == null ) selectedText = null;

    if ( selectedText == null || selectedText.isEmpty() )
    {
        copy2.setEnabled(false);
        cut1.setEnabled(false);
    }

    else
    {
        cut1.setEnabled(true);
        copy2.setEnabled(true);
    }
}

Upvotes: 1

akf
akf

Reputation: 39495

You should setEnabled(false) on each of these menu items when you create them.

Upvotes: 5

Related Questions