3

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

        }
    });
kleopatra
  • 51,061
  • 28
  • 99
  • 211
orange
  • 5,297
  • 12
  • 50
  • 71

3 Answers3

5

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

akf
  • 38,619
  • 8
  • 86
  • 96
  • This works, is there a better way? (It seems kind of tacky to me, it might just be me though). – orange Feb 11 '12 at 18:15
  • 1
    @Jeff - think of it this way: selection is a positive action that enables the menu items. When you start the app, no selection has taken place yet, so those items should be at their default state. Which is disabled. – kdgregory Feb 11 '12 at 18:29
1

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);
    }
}
-1

You can use JtextField.setHighlighter(null);