0

I have a JTextField. If I type something in it, I need to save that instantaneously. I have an addActionListener event linked to it, which saves the changes only if I press "ENTER" after typing something to it.

After the suggestions, I made the following changes in my code. I need to call addActionListener, but I am not sure how would I

mMaxLabelLength = new JTextField();
mMaxLabelLength.getDocument().addDocumentListener(this);

public void changedUpdate(DocumentEvent e)
{
    System.out.println("1");
    mMaxLabelLength.addActionListener(this);
}

public void removeUpdate(DocumentEvent e)
{
    System.out.println("2");
    mMaxLabelLength.addActionListener(this);
}

public void insertUpdate(DocumentEvent e)
{
    System.out.println("3");
    mMaxLabelLength.addActionListener(this);
}

    public void actionPerformed(ActionEvent e)
{
    // do something
    }
user1631306
  • 4,350
  • 8
  • 39
  • 74
  • 2
    [Listening for Changes on a Document](http://docs.oracle.com/javase/tutorial/uiswing/components/generaltext.html#doclisteners) - beware though, depending on what you are doing, you might make the UI "stutter" or become unresponsive while the user is typing – MadProgrammer Jan 11 '16 at 02:24
  • 1
    And [for example](http://stackoverflow.com/questions/33597878/set-typed-text-in-a-jlabel/33599932#33599932) – MadProgrammer Jan 11 '16 at 02:28
  • @MadProgrammer the example looks good to me. How would I call "addActionListener" under "removeUpdate". I already have defined "public void actionPerformed(ActionEvent e)" explicitly which are called by other buttons. So I don't want to write a class under "removeUpdate". I just want to call "addActionListener". I have edited my question – user1631306 Jan 11 '16 at 14:25
  • 1
    You wouldn't, you don't want to add a ActionListener each time the user types something – MadProgrammer Jan 11 '16 at 19:32

0 Answers0