Zajra11
Zajra11

Reputation: 43

returning a string to a textfield

i have a program which does this. A string is inputted by the user is stored as a String in an arraylist. When the user presses the up arrow, the most recently entered command is shown in the JTextField. Further presses of the up arrow will display other commands in the JTextField,ordered by the most recently entered until there are no more commands to display or the user stops.

Storing the string in the arraylist is working fine the only issue that i've got is with the Jtextfield only one command is shown in it when i press the up arrow even if i have typed multiple commands Can any body help below is the code for when the up arrow is pressed.

if (e.getKeyCode() == KeyEvent.VK_UP) 
        {
            for(int i = 0; i < history.list.size(); i++)
            {
                field.setText(history.list.get(i));
            }
        }

Thanks for your help, much appreciated.

Upvotes: 2

Views: 43

Answers (1)

user3437460
user3437460

Reputation: 17454

Your problem lies in this block of codes:

        for(int i = 0; i < history.list.size(); i++)
        {
            field.setText(history.list.get(i));
        }

This makes the field to always display the last element from your history list. Because it will iterate the entire list, hence it will always update the field with the last element from your list.

To solve the problem, you can keep a index variable. When key is pressed, update the index accordingly. Then set field accordingly:

if (e.getKeyCode() == KeyEvent.VK_UP) 
{
    index = (index + 1)% history.list.size();  //Ensure it stays within bounds
    field.setText(history.list.get(index));
}
else if (e.getKeyCode() == KeyEvent.VK_DOWN) 
{
    index = Math.max(0, index - 1);            //Ensure it stays within bounds
    field.setText(history.list.get(index));
}

Upvotes: 1

Related Questions