Reputation: 69
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.
Upvotes: 3
Views: 9557
Reputation: 1753
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
Upvotes: 2
Reputation: 7906
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
}
}
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.
Upvotes: 5