Reputation: 1
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.
Upvotes: 0
Views: 818
Reputation: 3609
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 + " ");
});
});
Upvotes: 1