[英]How can I create dynamic JLists?
I have multiple Jlist
components. 我有多个Jlist
组件。 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". 例如,第一个列表可能具有三个项目,分别是“ 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. 当我单击“ A”时,下一个列表应显示1、2、3、4、5等。当我单击“ B”时,下一个列表应显示7、8、9等。我需要使用这些列表这种逻辑。
The aim is to implement a GUI like this: 目的是实现这样的GUI:
In outline, 概括来说,
Add a ListSelectionListener
to the first JList
. 将ListSelectionListener
添加到第一个JList
。
In the selection handler, use setModel()
to set the second list's model to the correct ListModel
for the current selection. 在选择处理程序中,使用setModel()
将第二个列表的模型设置为当前选择的正确ListModel
。
list1.addListSelectionListener((ListSelectionEvent e) -> { if (!e.getValueIsAdjusting()) { list2.setModel(models.get(list1.getSelectedIndex())); } });
Similarly, add a ListSelectionListener
to the second JList
and update the third panel accordingly. 同样,将ListSelectionListener
添加到第二个JList
并相应地更新第三个面板。
A similar approach is shown here for ComboBoxModel
. 这里为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);
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.