简体   繁体   中英

how to retrieve item ID from JList

I have a JList, where it displays names according to the DB. Associated with these names are IDs. for eg., foodId = 1, foodName = Chinese.

If i click on an item on the JList, i need to capture the foodID associated with the clicked foodName. i know a variable is needed.

when i have that value, I can pass that value into another method to retrieve the relevant food items associated with that foodId. Assume that getters & setters are done.

I have only the following, & am stuck. Please advise thank you.

list_1.addMouseListener(new MouseAdapter() {
            @Override
            public void mouseClicked(MouseEvent evt) {              
                //alter text of Label acc to clicked item @ JList
                JList list = (JList)evt.getSource();
                System.out.println (list.getSelectedValue());

                //store int value of item clicked @ JList
                int temp = 0;
                temp = ???????????

                //populate JPanel
                Food food = new Food();
                JPanel panel = new JPanel();                
                panel.setBounds(153, 74, 281, 269);
                panel.add(food.populateWithButtons());              

                contentPane.add(panel);
            }
        });
        list_1.setBorder(new LineBorder(new Color(0, 0, 0), 0));
        //populate JList
        list_1.setModel(food.populateJList());



public ListModel populateJList()
    {
        DefaultListModel model = new DefaultListModel();

        ResultSet rs = null;
        DataAccessObject db = new DataAccessObject();
        db.setUp("customer");

        String dbQuery = "SELECT store_Owner_Id, food_Category FROM store_owner";       
        rs = db.readRequest(dbQuery);

        try
        {
            while (rs.next())
            {
                food_Category = rs.getString("food_Category");
                store_Owner_Id = rs.getInt("store_Owner_Id");
                model.addElement(food_Category);                

                System.out.println (store_Owner_Id);    //test DB conn & print retrieved items
                System.out.println (food_Category);     
            }                   
        }
        catch (Exception e)
        {
            e.printStackTrace();
        }
        db.terminate();
        return model;
    }   

Suggestions:

  • Don't populate the JList with Strings but rather ...
  • If you populate your JList with objects that contain both the name and the ID, then you're doing well.
  • You will likely want to give your JList a cell renderer that helps it to show the information from the object that you want the JList to display.
  • Then getting the ID is simply a matter of getting the selected item from the JList inside whatever listener you're using, casting it to the object type that in fact is, and then calling the getter method, such as getId() , assuming that objects of this type have this method, and then use your ID.

Note though that this tells us nothing useful:

list_1.setModel(food.populateJList());

If my suggestions don't help you answer your question, then please provide more useful information and code, information that will help us to fully understand your problem.


Edit 2

Your latest code shows that you're doing what I recommended that you not do:

while (rs.next())
{
    food_Category = rs.getString("food_Category");
    store_Owner_Id = rs.getInt("store_Owner_Id");
    model.addElement(food_Category);    // ****** here              

    System.out.println (store_Owner_Id);    
    System.out.println (food_Category);     
}

You're adding Strings to your DefaultListModel, and by doing this you lose all the other information that the database gave you.

Again do not add Strings to this model. Create a class that has two or more fields, one for the category String, and one for the owner ID, that has getters, setters, and a constructor that allows you to pass this information into objects of the class, create objects of this class in your while loop above, and add these to the JList model. Then give your JList a custom renderer which is better than giving the custom object a toString() method for this purpose.

  • Create a custom class, say called FoodInfo
  • Declare the DefaultListModel as one that accepts objects of this type, DefaultListModel<FoodInfo>
  • Then add objects of this type to the model:

eg,

DefaultListModel<FoodInfo> model = new DefaultListModel<FoodInfo>();

// ... other code to get database info

while (rs.next()) {
   String foodCat = rs.getString("food_Category");
   int id = rs.getInt("store_Owner_Id");
   FoodInfo foodInfo = new FoodInfo(foodCat, id);
   model.addElement(foodInfo);
}

Edit 3
As has been noted in comment by @dic19, don't use a MouseListener on the JList but rather use a ListSelectionListener as described in the JList Tutorial .

See Combo Box With Hidden Data . It will show you how to use a custom object without the need for a custom renderer. I know the title is "Combo Box" but the concept is identical for a JList.

When you use a custom renderer you break the default functionality of JList since you will no longer be able to select items using the keyboard. A properly designed GUI should allow the use to use the mouse or keyboard to select an item.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM