Detecting text selection in JTextArea

*爱你&永不变心* 提交于 2019-12-04 04:22:27

问题


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

        }
    });

回答1:


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




回答2:


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



回答3:


You can use JtextField.setHighlighter(null);



来源:https://stackoverflow.com/questions/9242620/detecting-text-selection-in-jtextarea

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