如何在java swing中显示对象列表作为JList ?



我们被要求在Java Swing中构建一个没有拖放的系统,我无法理解如何在JList中显示对象列表。我有一个GUI类,它创建了一个JFrame、JPanel和一个空JList,还有一个包含对象列表的逻辑类,可以通过logic.studentsList访问。我需要通过字段创建更多的学生对象,并在我的JList中显示它们,并添加到现有的studentsList(类型为ArrayList<Students>)。我应该将JList声明为JList对象类型Students吗?我找不到如何连接JList与对象列表的信息。我唯一的想法是从输入字段数据中创建新的Student对象,并将其传递给logic.stundentsList。但是如何在GUI中以JList的形式显示它呢?

  1. 创建要显示的对象列表
  2. 创建DefaultListModel对象来存储列表中的对象
  3. 创建一个JList对象,并将其模型设置为DefaultListModel。
  4. 将JList添加到JScrollPane以允许滚动,如果列表是长。
  5. 将JScrollPane添加到JFrame或JPanel等容器中显示JList
public class Example extends JFrame {

public Example() {
// Create a list of strings
List<String> items = new ArrayList<>();
items.add("Item 1");
items.add("Item 2");
items.add("Item 3");

// Create a DefaultListModel to store the strings
DefaultListModel<String> listModel = new DefaultListModel<>();
for (String item : items) {
listModel.addElement(item);
}

// Create a JList and set its model to the DefaultListModel
JList<String> jList = new JList<>(listModel);

// Add the JList to a JScrollPane to allow for scrolling
JScrollPane scrollPane = new JScrollPane(jList);

// Add the JScrollPane to a container such as a JFrame or JPanel
JPanel panel = new JPanel();
panel.add(scrollPane);
add(panel);

// Set the JFrame properties
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setTitle("Example");
pack();
setLocationRelativeTo(null);
setVisible(true);
}
}