Java modify vector items - java

I am using a vector to add my JList items to like below
public void addToList() {
Icon pingImage = new javax.swing.ImageIcon(getClass().getResource("/resources/icnNew.png"));
JLabel pingLabel = new JLabel("ID #231231", pingImage, JLabel.LEFT);
JPanel pingPanel = new JPanel(new FlowLayout(FlowLayout.LEFT));
pingPanel.add(pingLabel);
v.add(pingPanel);
menuList.setListData(v);
}
My Requirement is to update items within the vector depending on their ID. For example : On the above, i would like to change the ImageIcon for the ID #231231.
How could this be done?

As already said in the comments to your question, a Vector is the wrong data structure. Doing updates based on an identifier is asking for a Map. I would recommend against iterating through a list, looking for matching labels, since its an O(n) instead of O(log n) operation.

Related

Populating JComboBox using an MultiDimensional Array List

I have been trying to populate a Eclipse GUI Java JComboBox using an Array list using constructors without any luck. This is what I have tried thus far.
import item.Item;
import javax.swing.JComboBox;
import java.util.ArrayList;
public class SelectionScreen{
private JFrame frame;
static ArrayList< Item> list;
private String items;
public static void main (String[] args){
initialize();
}
public void initialize(){
list = new ArrayList< Item >();
list.add(new Item("Strawberry,200,.25,.75);
list.add(new Item("Banana,200,.25,1.00);
list.add(new Item("Oranges,200,.25,2.00);
JcomboBox comboBox = newJcomboBox();
ComboBox.setBounds(63,29,86,22)
frame.getContentPane().add(comboBox);
// here is where I tried to fill the combobox
//comboBox.setModel(new DefaultComboBoxModel(Item.getName()))); //Wrong
//comboBox.setModel(Item.getName); //Wrong
//the following only loads the last item in the list which is Oranges
for(Item i: list{
comboBox.setModel(new DefaultComboBoxModel(New String[] {
i.getName()}));
}
// tried making a different list to collect my fruits.
for(Item i: list){
list2[ i.getName()];
Item.length;
} //which was a complete fail.
I am at complete lost here and not very experienced with Java. I can load the items just fine using
comboBox.setModel(new DefaultComboBoxModel(new String[]{ "Strawberry","Banana","Oranges"}));
but I won't know what fruits are in the list when I import them from a text file.
Any help would be appreciated.
/*The following only loads the last item in the list which is Oranges.*/
for(Item i: list)
{
comboBox.setModel(new DefaultComboBoxModel(new String[] {
i.getName()}));
}
Don't keep creating a new ComboBoxModel inside the loop. You can't add more than one item to the model if you keep creating a new model. So you only see the last model created with the single item added to it. If you want to use this approach then you would create the model OUTSIDE of the loop and then just add items the model INSIDE the loop.
Actually you don't event need to create a combo box model. You can just add items directly to the combo box:
Something like:
for(Item i: list
{
comboBox.addItem( i.getName() );
}
Another option is to add the Item object directly to the combo box. Then you can use a custom renderer to control which property of the Item object is display in the combo box. Check out Combo Box With Custom Renderer for more information on this approach.
If you wish to show Item objects in a combobox then you should declare the JComboBox to store Item objects. That way you can easily add items without having to do any mucking around with models at all:
JComboBox<Item> itemsCombo = new JComboBox<>();
list.forEach(itemsCombo::add);
The value displayed in the combobox will be whatever is returned by Item.toString. If that's not what you want (because your toString returns a more complete description of the object - generally considered better practice) then it is fairly easy to write your own Custom Renderer.
The only hackish downside of the JComboBox API is that you've got to cast the selected item:
Item selectedItem = (Item)itemsCombo.getSelectedItem();
This is ugly and I wish the API didn't require it but it's a small price to pay to avoid having to define your own model.
You can, in fact, avoid the cast by:
Item selectedItem = itemsCombo.getItemAt(itemsCombo.getSelectedIndex());
But that's just about as ugly.
As an aside, this is one of several areas in which the standard Java tutorial and samples are quite out of date so there's no blame here at all for not knowing to use generics.

Linking Swing Components

My GUI
I need some kind of foreach loop to go through all of the components in the content pane and add the values into a map.
HashMap<String, String> items = new HashMap<String, String>();
The String from the Drop Down box will be the Key and the value will be the contents of the Day and Week JTextField components (maybe with a ';' so I can split later).
So far I can't figure out how to link the components together or if that is even possible (even if there is a hacky way around it).
Assuming that all your components are inside JPanel you can try this:
for(Component comp : jPanel1.getComponents()){
if(comp instanceof JComboBox){
JComboBox cb = (JComboBox)comp;
System.out.println("cb.getName() = "+cb.getName());
System.out.println("cb.getSelectedItem() = "+cb.getSelectedItem());
}
}

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.

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

How to transfer the elements from one JList to other JList in Java?

I have two JList on a swing GUI. Now I want that when a user clicks on a button (say TransferButton) the selected elements from one JList is added from the first JList to the second JList and remove those selected elements from the first JList.
The model doesn't know about selection.
The JList provides several methods to get the selected item or selected index. Use those methods to get the items and add them to the other list's model.
You have two JLists, then you also have their respective ListModels. Depending on how you implemented them you can just remove the elements from one model and add them to the other. Note, though, that the ListModel interface doesn't care for more than element access by default, so you probably have to implement add and remove methods there by yourself.
DefaultListModel leftModel = new DefaultListModel();
leftModel.addElement("Element 1");
leftModel.addElement("Element 2");
leftModel.addElement("Element 3");
leftModel.addElement("Element 5");
leftModel.addElement("Element 6");
leftModel.addElement("Element 7");
JList leftList = new JList(leftModel);
DefaultListModel rightModel = new DefaultListModel();
JList rightList = new JList(rightModel);
Let's imagine you have two JList components as described in the code above (left and right). You must write following code to transfer selected values from the left to the right JList.
for(Object selectedValue:leftList.getSelectedValuesList()){
rightModel.addElement(selectedValue);
leftModel.removeElement(selectedValue);
}

Categories