Adding an ActionListener to a JList

user1015127 picture user1015127 · Apr 10, 2011 · Viewed 29.9k times · Source

I have a JList with an array of strings. Basically it displays a restaurant menu. right next to the JList i have another JList which is empty. Whenever a user double clicks on a string in the first JList (where the menu is displayed) I want it to show up on the next JList which is right next to it.

how do i do that?

Answer

Bala R picture Bala R · Apr 10, 2011

You can try

final JList list = new JList(dataModel);
MouseListener mouseListener = new MouseAdapter() {
    public void mouseClicked(MouseEvent e) {
        if (e.getClickCount() == 2) {


           String selectedItem = (String) list.getSelectedValue();
           // add selectedItem to your second list.
           DefaultListModel model = (DefaultListModel) list2.getModel();
           if(model == null)
           {
                 model = new DefaultListModel();
                 list2.setModel(model);
           }
           model.addElement(selectedItem);

         }
    }
};
list.addMouseListener(mouseListener);