简体   繁体   中英

How to add event listener for when a new item in a JList is selected? Netbeans

I want to update some fields every time a new item is selected. I have tried using Focus Gained event listener and value changed listener but i can't get it to change when the selection is changed.

There is a simple example how you can achieve that using addListSelectionListener(ListSelectionListener listener) method. In example that I provided, overriden method just copies labels of selected elements of the list to the JTextField field - of course you can implement behavior you need to be performed when selection is being changed:

1) When using Java 7 or below:

JTextField field = new JTextField(7);
JList<String> list = new JList<>(new String[] {"a", "b", "c"});
list.addListSelectionListener(new ListSelectionListener() {
    @Override
    public void valueChanged(ListSelectionEvent e) {
        List<String> values = ((JList<String>)(e.getSource())).getSelectedValuesList();
        field.setText(""); // clears previous entry from the JTextField
        for(String value : values) {
            field.setText(field.getText() + value + " ");
        }
    }

});

2) Code of addListSelectionListener() when using Java 8 or above:

@Override
list.addListSelectionListener(e -> {
    List<String> values = ((JList<String>)(e.getSource())).getSelectedValuesList();
    field.setText("");
    values.forEach(value -> {
        field.setText(field.getText() + value + " ");
    });
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM