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

后端 未结 3 2100
栀梦
栀梦 2020-12-04 01:27

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 ActionLi

相关标签:
3条回答
  • 2020-12-04 02:03

    Yeah, but what is a document listener and how do you use it? You're not really answering the question.

    I have a JTextField in my app's user interface. When the user makes any change to it, I want a nearby JCheckBox to be checked. The purpose is to tell the app to USE the value that was entered. Users often enter a value there but if they don't explicitly tell the app to use it then the app continues to ignore it. Instead of "training" users I'm supposed to follow the principle of least astonishment and automatically check the "Use this value" box.

    But how do I listen for a change? Can't you guys just tell me the easy way, instead of "educating me" about document listeners?

    0 讨论(0)
  • 2020-12-04 02:07

    From an answer by @JRL


    Use the underlying document:

    myTextField.getDocument().addDocumentListener();
    
    0 讨论(0)
  • 2020-12-04 02:20

    Documents are the mechanisms java swing uses to store the text inside of a JTextField. DocumentListeners are objects that implement the DocumentListener interface and thus make it possible for you to list to changes in the document, i.e. changes in the text of the JTextField.

    To use the document and documentlistener capabilities, as suggested above extend your class (probably but not necessarily a JFrame) so that it implements the DocumentListener interface. Implement all the methods for the interface (most likely your java ide can do that semi-automatically for you. FYI, the DocumentListener interface has three methods, one for inserting characters (into the text field), one for removing characters, and one for changing attributes. You are going to want to implement the first two as they are called when characters are added (the first one) or deleted (the second one). To get the changed text, you can either ask the document for the text, or more simply call myTextField.getText().

    C'est tout!

    Phil Troy

    0 讨论(0)
提交回复
热议问题