Get text element inside jlist variable?

Despite a lot of research, I cannot find the answer or decide how to get the selected text element inside the JList for the variable. So I would help a little. I tried to select the index of the selected item and delete the items using this code, and this works fine, but as I wrote, I want the selected text to change after clicking the button. Thanks!

int index = list.getSelectedIndex(); model.removeElementAt(index); 

Parts of my JList code:

 model = new DefaultListModel(); list = new JList(model); list.setSelectionMode(ListSelectionModel.SINGLE_INTERVAL_SELECTION); JScrollPane listScroller = new JScrollPane(list); listScroller.setPreferredSize(new Dimension(430, 60)); 

Parts of my actionlistener code:

 // Select customer if(event.getSource() == buttonSelectCustomer){ int index = list.getSelectedIndex(); // Just for test model.removeElementAt(index); // Just for test int number = model.getSize(); // Just for test //String selectedText = list.getSelectedValue(); // Not working! } 
+6
source share
3 answers

Use the ListModel#getElementAt(int) method with the currently selected index. If you are sure that your model contains only String instances, you can directly apply it to String , as well as

+7
source

You cannot get the selected text because you are trying to get it after deleting the selected item. you can change your code:

 if(event.getSource() == buttonSelectCustomer) { int index = list.getSelectedIndex(); // Just for test model.removeElementAt(index); // Just for test int number = model.getSize(); // Just for test String selectedText = list.getSelectedValue(); // Not working! } 

in my code:

 if(event.getSource() == buttonSelectCustomer) { String selectedText = (String)list.getSelectedValue(); // it works int index = list.getSelectedIndex(); // Just for test model.removeElementAt(index); // Just for test int number = model.getSize(); // Just for test } 

then it works.

+2
source

It’s easy to get an element of a selected index. Here is a simple piece of code:

 String[] string = new String[]{"Hello","Hi","Bye"}; JList list = new JList(string); 

Now use the following code to get the selected item as a string:

 String item = list.getSelectedIndex().toString(); 
-1
source

Source: https://habr.com/ru/post/906285/


All Articles