简体   繁体   中英

JTextField not updating user input in for-loop

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] );  

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.

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