Hi All. Please I need your help.

I have just started work as a Software Engr.
I have a project at hand which includes placing different image icons on a JLabel component depending on which element of a JList is selected.

I used single selection model. I tried using if-else construct to specify which imageicon should be placed on the label if a particular element is selected from the JList, but this did not work. I then commented out the if-else statementst to see if I could get this work. Selection occured but the problem is that only one imageicon is being displayed for whichever element selected.

I have been on this problem for some time now while trying to read up every thing I could find on JList component handling. The deadline for me to come up with the solution to this project is next week, so I need as much help as I can get to come up with the solution.

Any help would be highly appreciated.

Thank you.
KingsKidy.

Some coding would be welcome, reading from magic ball to locate your code issues is difficult these days ;)

If you can provide some code we will try to help you...

Thank you. The following is the cose snippet of what I intended to do:

[//process the Classic button event
  cbtn1.addActionListener(new ActionListener(){
          public void actionPerformed(ActionEvent evt)
          {
              //String[] Str1 = {"John","James","Moses","Nick","Paul"};
              //trying something new here
               String[] cdtit = displayClassicTitles();
               titlelisting = new JList(cdtit);
               
               titlelisting.setVisibleRowCount(3);
  
               //does not allow multiple selections
               titlelisting.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
  
                scrollPane = new JScrollPane(titlelisting);
                   // frame.add(scrollPane, BorderLayout.CENTER);
                 ListAndLabelPanel.add(scrollPane,BorderLayout.SOUTH);
                 //  create an image icon
 
                 ImageIcon cdImage = new ImageIcon("C:/CDGraphics/GospelGifs/EasyStars.Gif");
  
              //add the image icon to a label and set label text
               lblC = new JLabel(cdImage);
               lblC.setText("Pic of selected title");
               ListAndLabelPanel.add(lblC,BorderLayout.CENTER);
 
               panelC.add(ListAndLabelPanel,BorderLayout.CENTER);

                 //now  add the center panel to the frame
                frame.add(panelC,BorderLayout.CENTER);
              
                frame.setVisible(true);
              
               //Handle the JList Event
          titlelisting.addListSelectionListener(new ListSelectionListener(){
            public void valueChanged(ListSelectionEvent event)
             {
                 if(!event.getValueIsAdjusting())
                  {
                     if(titlelisting.getSelectedValue()=="OxbridgeBaby")
                      {
                          ImageIcon cdImage1 = new ImageIcon("C:/CDGraphics/ClassicGifs/OxbridgeBaby.Gif");
                          lblC.setIcon(cdImage1);
                          ShoppingCart selectedItem = new ShoppingCart();
                          selectedItem.setSelectedTitle1(titlelisting.getSelectedValue().toString());
                          selectedItem.setTitlePrice1("$10.00");
                          selectedItem.setVisible(true);                                    
                      }else if(titlelisting.getSelectedValue()=="BrainyBaby")
                       {
                         ImageIcon cdImage2 = new ImageIcon("C:/CDGraphics/ClassicGifs/BrainyBaby.Gif");
                         lblC = new JLabel(cdImage2);
                         ShoppingCart selectedItem = new ShoppingCart();
                         selectedItem.setSelectedTitle2(titlelisting.getSelectedValue().toString()); 
                         selectedItem.setVisible(true);
                       }else if(titlelisting.getSelectedValue()=="ADozenRoses")
                        {
                           ImageIcon cdImage3 = new ImageIcon("C:/CDGraphics/ClassicGifs/ADozenRoses.Gif");
                           lblC = new JLabel(cdImage3);
                           ShoppingCart selectedItem = new ShoppingCart();
                           selectedItem.setSelectedTitle3(titlelisting.getSelectedValue().toString());
                        }
                         else{ }   
                                
                      }
                    }
                });  
                
             }
  });

Plesae I want to know whether the if-else construct is the best approah in this regard; if not how else should I approach it.

Thank you.

----
KingsKidy.

You cannot compare Strings using '==' you must use the String class's equals method.

if(titlelisting.getSelectedValue()=="OxbridgeBaby")

I would recommend making a class to represent those items that appear in the list. The toString() method of that class should return the description you wish to see in the list. On selection, you can access that object through getSelectedValue() and read the image path from that object.

HashMap would be another possibility if the only data needed for each item is simply the title and image.

Thank you all for helping out.
The String class's equals method did the job. I replaced the '==' with equals() and got the result I wanted.
I am grateful that you are there to help.
---
KingsKidy.

You're going to hard-code all of that data into an if-else structure in a production app? If there is any more than what you posted, you're making a real mess for yourself to maintain.

Thank you Ezzaral for your last post. However the list elements are not hard-coded into the app. They were actually read in from a file -a separate method handled that. I only used the if-else construct to compare the elements selected from the list with the contents of the file.

KingsKidy.

If I'm right in what are Ezzaral intentions then with use of specifically build class for above task, store it in ArrayList, you could use for each to take on job of iterating through and checking which value is selected. Depending on that manipulate rest of the action flow.

I only used the if-else construct to compare the elements selected from the list with the contents of the file.

Then you're still hard-coding what to do with each item as it's selected and that negates the reason for storing them in a file at all. Here is a very small example of the design I mentioned above. You need an "Item" class to hold the data for each of those items and you can use that directly within the JList

import java.awt.BorderLayout;
import java.util.ArrayList;
import java.util.List;
import javax.swing.DefaultListModel;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JList;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;

public class ListExample extends JFrame {
    JList itemListing;
    JLabel pathLabel;

    public ListExample() {
        getContentPane().setLayout(new BorderLayout());
        setDefaultCloseOperation(EXIT_ON_CLOSE);

        // Build your ListModel from the items list.
        // You could very easily make this custom
        // ListModel class to handle all of the data retrieval.
        DefaultListModel model = new DefaultListModel();
        List<ListItem> fileItems = getItemsFromFile();
        for (ListItem item : fileItems){
            model.addElement(item);
        }
        itemListing = new JList(model);
        itemListing.addListSelectionListener(new SelectionListener());
        getContentPane().add(itemListing, BorderLayout.NORTH);

        pathLabel = new JLabel();
        getContentPane().add(pathLabel, BorderLayout.SOUTH);

        setBounds(100,100,300,200);
    }

    /** Just an example, you would retrieve these items from
     * file, database, whatever.
     */
    private List<ListItem> getItemsFromFile() {
        List<ListItem> items = new ArrayList<ListItem>();
        items.add(new ListItem("One thing","c:\\someDir\\oneThing.jpg"));
        items.add(new ListItem("Another thing","c:\\someDir\\anotherThing.jpg"));
        items.add(new ListItem("Big shiny thing","c:\\someDir\\shiny.jpg"));
        return items;
    }

    /** This is your data class. It should hold all of the data that you need 
     * to display or work with for each item.
     */
    class ListItem {
        String description;
        String path;

        public ListItem(String description, String path){
            this.description = description;
            this.path = path;
        }

        public String getPath(){
            return path;
        }
        public String toString(){
            return description;
        }
    }

    /** Small listener for your JList */
    class SelectionListener implements ListSelectionListener{
        public void valueChanged(ListSelectionEvent e) {
            if (itemListing.getSelectedIndex()>-1){
                ListItem selectedItem = (ListItem)itemListing.getSelectedValue();
                pathLabel.setText( selectedItem.getPath() );
            }
        }
    }

    public static void main(String args[]) {
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new ListExample().setVisible(true);
            }
        });
    }
}

If you already have a class that represents all of those items and cannot use it directly in the list, then you could change the ListItem class to be a tiny wrapper for your real item class that provides the methods needed to work with it in the JList.

Comments
Good advice, I doubt he will take it though.
Looks good (and shiny) to me.
This article has been dead for over six months. Start a new discussion instead.