简体   繁体   中英

How to enter data to swing.JTextField without pressing the enter key?

I'm building a Gui using net beans (Java) and my question is how to get the string in the text field to the variable without pressing the Enter key? I wrote this code:

private void idTextBoxActionPerformed(java.awt.event.ActionEvent evt)   {                                          

   this.Id  =  evt.getActionCommand();
}

The problem is that if I just enter the text and move to the next text field, the data doesn't go into the Id variable, if I press Enter everything OK.

Pressing Enter invokes an ActionEvent from that textfield which you listen for in your actionPerformed method and that is why your code only works in that scenario.

You could use a FocusListener to acheive what you want. You will want to listen for the focusLost event, which is when you move away from the textfield.

class foo implements FocusListener {
    JTextField textField = new JTextField("A TextField");
    textField.addFocusListener(this);

    public void focusGained(FocusEvent e) {
       // Do whatever you want
    }

    public void focusLost(FocusEvent e) {
       // Save the text in the field to your id variable
    }
}

EDIT

The following tutorial shows how to use a formatted textfield . You can ignore the formatting bit and focus on the propertyChangeListner aspect of it. The idea is the same as my first example but using a different type of listener.

You could use the action event or focus event to track the changes at component level. But if its the text changes that you are interested in, then you should consider using a DocumentListener . Read the tutorial here

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM