removing multiple selections from JList - java

I have a JList with some elements where multiple selection is allowed. Before these elements are added to the JList, some information about them is being stored in a static HashMap in a separate class. When more than 1 items are selected and the 'Remove selected' button is pressed, I am trying to remove the selected items (which works fine) and also delete their records from the HashMap. For some reason though, if I select more than 1 elements, only the first record in the HashMap is removed. I don't understand how this works for the JList but doesn't work for the HashMap. My code below:
remove.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
Object[] selectedElementsValues = jList.getSelectedValues();
for (int i = 0; i < selectedElementsValues.length; i++) {
System.out.println(jList.getSelectedValue().toString());
System.out.println(PersonClass.map.get(jList.getSelectedValue().toString()));
PersonClass.map.remove(jList.getSelectedValue().toString());
System.out.println(PersonClass.map);
}
It works fine if I select only one item at a time and remove it. But not with multiple selection. The items from the JList are removed properly, though, so I don't see why it doesn't do the same for the map.
Thx

The problem is that the loop that removes items from the map uses jList.getSelectedValue().toString(), when the jList selection is not modified. You can use the selection array you obtained earlier:
for (Object o : selectedValues) {
PersonClass.map.remove(o.toString());
}
Note that getSelectedValues() is deprecated, and you should use getSelectedValuesList() instead.

Related

Correct method to swap two rows in the SWT table

I am using the SWT library in my software, not in Eclipse. I need to swap two rows at runtime in a table SWT that I populated via an array. I used the following method:
I take the array
swap two elements(with Collection.swap)
I empty the table
I reinsert the elements from the array
I'd like to know if there is a better method, do I have to reinsert all the elements in the table? because when there are so many rows the visual effect is evident and it seems a waste since I would like to swap only two rows at a time.
Here is the code:
if(table.getSelectionIndices()[0]<table.getItemCount()&&table.getSelectionIndices()[0]>0) {
Collections.swap(pluginsTmp, table.getSelectionIndices()[0], table.getSelectionIndices()[0]-1);
int nextSelectionIndex=table.getSelectionIndices()[0]-1;
updateTable();
table.setSelection(nextSelectionIndex);
}
In this case it serves to "go up" the selected item, exchanging it with those above
public void updateTable() {
table.removeAll();
for(int a=0;a<pluginsTmp.size();a++) {
Plugin p = pluginsTmp.get(a);
TableItem item = new TableItem(table, SWT.NONE);
item.setText(0,p.getClass().getName().toString());
item.setText(1,p.getVersionMajor()+"."+p.getVersionMinor()+"."+p.getVersionBuild());
item.setText(2,p.getAuthor());
item.setText(3,(p.isEnabled())?"Enabled":"Disabled");
item.setData("className",p.getClass().getName().toString());
item.setData("status",(p.isEnabled())?"1":"0");
}
}
Thank you all
Just call setText and setData on the two table items that have changed.
You can get an existing TableItem from the table using
TableItem item = table.getItem(index);
where index is the row in the table.

JList setSelectedValue not working

I have a JList in Swing working bad. I list all items from Database into the list with no problem with this code.
My code:
Integer index = null;
DefaultListModel<String> model = new DefaultListModel<String>();
index = DataBase.getIndex1(cbActivity.getSelectedItem().toString());
activities = DataBase.getIndex2(index);
for(MapActivity mapActitivy : activities)
{
model.addElement(mapActivity.getActivity().toString());
}
jList.setModel(model);
But now, I would like to select individual or multiple selection, but nothing I tried works. I tried:
jList.setSelectedValue("Ball", true);
//jList.setSelectedIndex(2);
jList.setSelectionBackground(Color.red);
But nothing happen. Just the list on screen with nothing selected. Single or multiple.
Any help?
Try this:
setSelectedIndex(1); // here use index of items
or if it does not work use below one:
setSelectedItem("ball") // here use name of item.

Clean model of a JList java

I try to fill a JList but first remove existing elements to avoid repeated records.
LLenarGrid that method call on a button to show that is to display objects in arraylist and JList but if I have 5 elements and give twice the button I get 10 doubles me as if I did not clean up the model
I leave my method, if I could help? or that I'm doing wrong, Thanks
public void LlenarGrid()
{
listapersonas.setModel(new DefaultListModel());
DefaultListModel listModel = (DefaultListModel)listapersonas.getModel();
listModel.removeAllElements();
for (clsPersona d : personas) {
listModel.addElement(d.RetornaPersona());
}
listapersonas.setModel(listModel);
listapersonas.clearSelection();
}
You do not have to set the model to list multiple times.
you can remove all element using below which you are already doing.
model.removeAllElements();
As suggested by John Bollinger check the personas List.

Stuck adding list selection listener to program [duplicate]

This question already has an answer here:
Showing a counter dynamically for JList items highlighted
(1 answer)
Closed 6 years ago.
I asked a similar question yesterday and while I got some direction I am now stuck. I have a program that contains a GUI with two lists which are side-by-side. The first list (which I will refer to as left) contains a number of items which are parsed from an uploaded file.
The other list (I'll call the right list) is empty by default. The user can use some buttons to transfer items between the two lists. At runtime the items in the right list will be kept and the left list will be discarded. Now I have successfully added a counter that shows dynamically the total count of items for each list.
I had an idea yesterday that I want to add another dynamic counter that will show the user how many items are selected in the left list (but haven't been moved yet). The reason for this is that users may have very large lists (300+ items) and need to move a certain amount (like 50).. Having a counter to show how many items they have currently selected will save them a little time.
I understand to do this I need to use a list selection listener that will have a method to set the text of my JLabel. The problem is I can't figure out the method to get the size of the list.
Here is where my list is created.
input = new DefaultListModel();
Here it is populated with an array of items that was filled during a buffered writer based on the upload file.
String[] inputItems = new String[MainWriter.entryDetails.size()];
inputItems = MainWriter.entryDetails.toArray(inputItems);
for(int i = 0; i < inputItems.length; i++){
input.addElement(inputItems[i]);
}
Creating the list:
inputDetails = new JList(output);
inputDetails.setVisibleRowCount(10);
inputDetails.setFixedCellHeight(20);
inputDetails.setFixedCellWidth(400);
inputDetails.setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION);
//Creates a new scroll pane for the inputDetails.
JScrollPane list2 = new JScrollPane(inputDetails);
Here is my attempt at creating the list selection listener..
inputDetails.addListSelectionListener(new ListSelectionListener(){
#Override
public void valueChanged(ListSelectionEvent arg0) {
selectedCount.setText(inputDetails.);
}
});
As you see I'm not sure what the best method would be to set the text to the currently selected items.
I believe that is enough information to illustrate my problem. I want to have the line Selected Items and then dynamically say how many items in the left list the user has highlighted.
Any help would be greatly appreciated.
EDIT:
As suggested I added the following:
inputDetails.addListSelectionListener(new ListSelectionListener(){
#Override
public void valueChanged(ListSelectionEvent arg0) {
String counter = Integer.toString(inputDetails.getSelectedIndices().length);
selectedCount.setText("Currently Selected Transactions: "+counter);
}
});
however the JLabel does not appear to be updating, can someone advise me on the problem?
In the listener, selectedCount.getSelectedIndices().length will tell you how many items are currently selected.

Is there another way to remove all items of a JComboBox then removeAllItems()?

Is there another way to remove all items of a JComboBox then removeAllItems()? I use 2 JComboBoxes in mij app and when you select an item from the first combobox the related items should then be shown in the second combobox. When I do this, the items just keep appending after the ones that were already there. When I then first try to clear the combobox by using removeAllItems(), the second combobox is empty and stays empty whenever I change the first combobox... The first combobox keeps all its values... Does anyone see my problem?
festival is the JComboBox:
private JComboBox festival;
private JComboBox zone;
...
public void fillFestivalList(){
festival.removeAllItems();
List festivals = OP.fillFestivalList();
for(Object fest: festivals)
festival.addItem(fest.toString());
}
public void fillZoneList(String festival){
zone.removeAllItems();
List zones = OP.fillZoneList(festival);
for(Object zoneItem: zones)
zone.addItem(zoneItem.toString());
}
Regarding,
Is there another way to remove all items of a JComboBox then removeAllItems()?
Simply give the JComboBox a new model.
I would create a new DefaultComboBoxModel<T>, fill it with the newest entries, and then call setModel(...) on my JComboBox, passing in the new model when desired.
You can also Remove all the items in this way ,
but better to Give JCombobox a new DefaultComboBoxModel like the way #Hovercraft Full Of Eels said
int itemCount = combo.getItemCount();
for(int i=0;i<itemCount;i++){
combo.removeItemAt(0);
}

Categories