Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Adding an ActionListener to a JList

Tags:

swing

jlist

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?

like image 221
user1015127 Avatar asked Apr 10 '11 01:04

user1015127


2 Answers

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);
like image 174
Bala R Avatar answered Sep 30 '22 14:09

Bala R


You may also want to do it with the Enter key pressed by adding a KeyListener:

jlist.addKeyListener(new KeyAdapter(){
public void keyPressed(KeyEvent e){
    if (e.getKeyCode() == KeyEvent.VK_ENTER){
   //do what you want to do    
}
}
});

I know that this is not for a double click but some people want to do it with the Enter button instead as I wanted to do.

like image 37
Alan Deep Avatar answered Sep 30 '22 13:09

Alan Deep