Detecting text selection in JTextArea

我的未来我决定 提交于 2019-12-01 21:49:45

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

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

You can use JtextField.setHighlighter(null);

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!