本文介绍了始终将文本保留在java textField中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在处理java textField的输出时,我要求保持输入文本始终处于选中状态.我编写的代码可以完美工作,只是始终选择其中的文本.请帮助我修改代码,以便textField中的文本始终保持选中状态.我已经使用了'textField.selectAll();',但是在这里不起作用.

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

推荐答案

添加 DocumentListener 到文本文档,那么即使用户删除或插入值,也始终会选择文本.

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

这篇关于始终将文本保留在java textField中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-19 02:48