e784. 监听对JList选择变动

When the set of selected items is changed, either by the user or programmatically, a list selection event is fired.

    // Create a list
    String[] items = {"A", "B", "C", "D"};
    JList list = new JList(items);
    
    // Register a selection listener
    list.addListSelectionListener(new MyListSelectionListener());
    
    class MyListSelectionListener implements ListSelectionListener {
        // This method is called each time the user changes the set of selected items
        public void valueChanged(ListSelectionEvent evt) {
            // When the user release the mouse button and completes the selection,
            // getValueIsAdjusting() becomes false
            if (!evt.getValueIsAdjusting()) {
                JList list = (JList)evt.getSource();
    
                // Get all selected items
                Object[] selected = list.getSelectedValues();
    
                // Iterate all selected items
                for (int i=0; i<selected.length; i++) {
                    Object sel = selected[i];
                }
            }
        }
    }

 

Related Examples
posted @ 2018-09-06 08:47  borter  阅读(385)  评论(0编辑  收藏  举报