问题
I have multiple Jlist
components. When an item in the first list is selected, the next list should dynamically display a new set of possible selections.
For example, the first list might have three items which are "A" ,"B" ,"C". When I click "A", the next list should show 1, 2, 3, 4, 5, etc. When I click "B" the next list should show 7, 8, 9, etc. I need these lists to work on this logic.
The aim is to implement a GUI like this:
回答1:
In outline,
Add a ListSelectionListener to the first JList.
In the selection handler, use
setModel()
to set the second list's model to the correctListModel
for the current selection.list1.addListSelectionListener((ListSelectionEvent e) -> { if (!e.getValueIsAdjusting()) { list2.setModel(models.get(list1.getSelectedIndex())); } });
Similarly, add a
ListSelectionListener
to the secondJList
and update the third panel accordingly.
A similar approach is shown here for ComboBoxModel
. This related example uses a similar approach to display a file system tree in columns.
import java.awt.EventQueue;
import java.awt.GridLayout;
import java.util.ArrayList;
import java.util.List;
import javax.swing.DefaultListModel;
import javax.swing.JFrame;
import javax.swing.JList;
import javax.swing.JPanel;
import javax.swing.event.ListSelectionEvent;
/** @see https://stackoverflow.com/a/41519646/230513 */
public class DynamicJList {
private final JList<String> list1 = new JList<>(new String[]{"A", "B"});
private final JList<String> list2 = new JList<>();
private final List<DefaultListModel> models = new ArrayList<>();
private void display() {
JFrame f = new JFrame("DynamicJList");
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
DefaultListModel<String> model1 = new DefaultListModel<>();
model1.addElement("A1");
model1.addElement("A2");
model1.addElement("A3");
models.add(model1);
DefaultListModel<String> model2 = new DefaultListModel<>();
model2.addElement("B1");
model2.addElement("B2");
models.add(model2);
list2.setModel(model1);
list1.addListSelectionListener((ListSelectionEvent e) -> {
if (!e.getValueIsAdjusting()) {
list2.setModel(models.get(list1.getSelectedIndex()));
}
});
JPanel panel = new JPanel(new GridLayout(1, 0));
panel.add(list1);
panel.add(list2);
f.add(panel);
f.pack();
f.setLocationRelativeTo(null);
f.setVisible(true);
}
public static void main(String[] args) {
EventQueue.invokeLater(new DynamicJList()::display);
}
}
来源:https://stackoverflow.com/questions/41514529/how-can-i-create-dynamic-jlists