[ACCEPTED]-Adding an ActionListener to a JList-jlist

Accepted answer
Score: 13

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

0

Score: 2

You may also want to do it with the Enter 4 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 3 that this is not for a double click but 2 some people want to do it with the Enter 1 button instead as I wanted to do.

Score: 0

I have done it already in your code in the 10 other question? [link] I want to add an action listener from one JList to another JList and how can a JList appear with out any text inside?

The only think you 9 must do there is to put it into the @Bala 8 R's if statement doing the check of number 7 of clicks:

if (e.getClickCount() == 2) {

//your 6 code

}

Actually you would be better to use 5 addElement(selectedItem); method, as in 4 the @Bala R's code instead of add(orderList.getModel().getSize(), selectedItem); in 3 my code. Both add the item to the end but 2 addElement looks nicer and you do not need 1 to retrieve the model's size.

Oi, Boro.

Score: 0
public void addActionListener(final ActionListener al) {

    jList.addKeyListener(new KeyAdapter() {
        public void keyPressed(KeyEvent e) {
            if (e.getKeyCode() == KeyEvent.VK_ENTER) {
                al.actionPerformed(new ActionEvent(e.getSource(), e.getID(), "ENTER"));
            }
        }
    });

    jList().addMouseListener(new MouseAdapter() {
        public void mouseClicked(MouseEvent e) {
            if (e.getClickCount() == 2) {
                al.actionPerformed(new ActionEvent(e.getSource(), e.getID(), "ENTER"));
            }
        }
    });

}

0

More Related questions