Keeping the text in a java textField always selected

心不动则不痛 提交于 2019-12-24 08:42:19

问题


While processing output from a java textField, I require to keep the input text always selected. The code I wrote works perfectly except keeping the text in it always selected. Kindly help me to amend the code so that text in the textField always remains selected. I have used ' textField.selectAll();', but it does not work here.

private class ButtonClickListener implements ActionListener{

    public void actionPerformed(ActionEvent e) {
        String command = e.getActionCommand();  
        if( command.equals( "OK" )) {  

            String text = textField.getText();
            textField.selectAll(); 
            textArea.append(text + newline); 

            System.out.print(text);

            //Make sure the new text is visible, even if there
            //was a selection in the text area.
            textArea.setCaretPosition(textArea.getDocument().getLength());
        }
    }   
}

回答1:


Add a DocumentListener to the text document, then the text always will be selected even if the user remove or insert a value.

textfield.getDocument().addDocumentListener(new DocumentListener(){
     @Override
     public void removeUpdate(DocumentEvent e){
         textfield.selectAll();
     }   

     @Override
     public void insertUpdate(DocumentEvent e){
         textfield.selectAll();
     } 

     @Override
     public void changedUpdate(DocumentEvent e){
      //nothing to do..
     }

});

Read more in How to wirte a Document Listener



来源:https://stackoverflow.com/questions/23701113/keeping-the-text-in-a-java-textfield-always-selected

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