-1

I'm trying to figure out how to make the box of the new data that was entered into my List after into a selected box after entering it. I implemented the getSelectionModel() method to where I can click on any item of the list but I want the new data that I entered to be selected (to have the blue/gray box around it) after I add new data. I have this code that adds new data into the list but I'm not sure if listView.getSelectionModel().select(name); is the way to get the result that I want.

String newLine = name + "," + artist + "," + year + "," + album;
obsList.add(name.trim() + " " + artist.trim());
writeToFile(newLine);
nameBox.setText(name);
artistBox.setText(artist);
albumBox.setText(year);
yearBox.setText(year);
listView.getSelectionModel().select(name); //this is what I added to try to select the box after I added  new info
sortOBS();

This is how my List pops up as when I run code.

This is how my List pops up as when I run code.

This is how my List looks like after I enter new data.

After I add the song it just has the previous selection highlighted. I want the new song to be highlighted.

I want the new data that I entered to be selected after I add to the list. In other words, how do I get the item that I added to be selected (blue/gray box around it)after entering new data?

delmontic
  • 21
  • 4

1 Answers1

1

Your code doesn't work because the select() method takes an integer describing the index of an element rather than the actual element.

You need to retain the element that you just added so that you can find the index later. Instead of adding the element anonymously like this:

obsList.add(name.trim() + " " + artist.trim());

name the element and then add it, like this:

String entry = name.trim() + " " + artist.trim();
obsList.add(entry);

Now, instead of this:

listView.getSelectionModel().select(name); // wrong

you can do this:

listView.getSelectionModel().select(obsList.indexOf(entry));

You might prefer to be a bit lazy and assume the index of each new entry. Since you just do obsList.add() without specifying a position, that means that you're always adding to the end of the list. The index of the newly added element will always be obsList.size() - 1, so you can do:

listView.getSelectionModel().select(obsList.size() - 1);
MarsAtomic
  • 10,436
  • 5
  • 35
  • 56