Adding an ActionListener to a JList

帅比萌擦擦* 提交于 2019-12-19 18:28:03

问题


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?


回答1:


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



回答2:


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.




回答3:


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

}



回答4:


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.



来源:https://stackoverflow.com/questions/5609200/adding-an-actionlistener-to-a-jlist

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