Adding an ActionListener to a JList

隐身守侯 提交于 2019-12-01 17:10:44

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

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.

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

}
Boro

I have done it already in your code in the 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 must do there is to put it into the @Bala R's if statement doing the check of number of clicks:

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

//your code

}

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

Oi, Boro.

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!