Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
252 views
in Technique[技术] by (71.8m points)

java - Let ActionListener listen for change in JTextField instead of only enter?

So as you may know, if you have a text field and you add an ActionListener to it, it will only listen to the keypress of the enter button. However, I want to let my ActionListener listen to changes in text of the . So basically I've got this:

    public static JPanel mainPanel() { 
    JPanel mainp = new JPanel(); 
    JTextArea areap = new JTextArea("Some text in the textarea"); 
    JTextField fieldp = new JTextField("Edit this"); 
    areap.setEditable(false); 
    fieldp.addActionListener(new ActionListener() {

        @Override
        public void actionPerformed(ActionEvent e) {
            // TODO Auto-generated method stub
             if(//change in textfield, for instance a letterpress or space bar)
                   { 
                        //Do this
                   } 
        }
    });
    mainp.add(areap);
    mainp.add(fieldp); 
    return mainp;
}

Any way I can listen to changes in text (like documented in the actionPerformed event)?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

From an answer by @JRL


Use the underlying document:

myTextField.getDocument().addDocumentListener();

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...