Reputation: 141
My for loop is not updating, I'm getting the output "mmmmmm" or "ffffff" of the same letter the user inputs each time. I want it to constantly update the next letter each time like this:
user input: m
user input: f
user input: d
output: "Letters Used: mfd"
int j = 0;
String []used = new String[6];
for(j = 0; j<6; j++){
used[j] = tf.getText(); //get user input
}
jl2.setText("Letters Used: " + used[0] + used[1] + used[2] + used[3] + used[4] + used[5] );
Upvotes: 1
Views: 230
Reputation: 47058
You shouldn't be using a for-loop for this. JTextField
has built in callbacks for text changes with DocumentListener
:
tf.getDocument().addDocumentListener(new DocumentListener() {
public void changedUpdate(DocumentEvent e) { // text was changed
jl2.setText("Letters Used: " + tf.getText());
}
public void removeUpdate(DocumentEvent e) {} // text was deleted
public void insertUpdate(DocumentEvent e) {} // text was inserted
});
Update:
If you want to only respond on Enter
presses, you can use an ActionListener
which is called on Enter
presses:
jl2.setText("Letters Used: ");
tf.addActionListener(new ActionListener(){
@Override public void actionPerformed(ActionEvent e){
jl2.setText(jl2.getText() + tf.getText());
}
});
Note: Actually, ActionEvent
is triggered by the system's look and feel "accept" action. In most cases, this is the enter key.
Upvotes: 5