英文:
How to display a list of objects as a JList in java swing?
问题
I have translated the requested content for you:
我们被要求在Java Swing中构建一个系统,不使用拖放,我不明白如何在JList中显示对象列表。
我有一个GUI类,它创建了一个JFrame、一个JPanel和一个空的JList,还有一个逻辑类,其中包含对象列表,可以通过logic.studentsList访问。
我需要通过字段创建更多的学生对象,并将它们显示在我的JList中,并添加到现有的studentsList(其类型为ArrayList<Students>)。
我应该将我的JList声明为JList对象类型Students吗?我找不到如何将JList与对象列表连接的信息。
我唯一的想法是从输入字段数据创建新的学生对象,然后将其传递给logic.studentsList。但如何在GUI中显示它也作为JList?
英文:
We are asked to build a system in Java Swing no drag and drop and I cannot understand how to display a list of objects in a JList.
I have a GUI class that creates a JFrame, JPanel, and an empty JList as well as a logic class with list of objects, which can be accessed via logic.studentsList.
I need to create more student objects via fields and display them in my JList and add to the existing studentsList (which is of type ArrayList<Students>).
Should I declare my JList as JList object type Students? I can't find information of how to connect JList with object list.
My only idea is to create new Student object from input fields data and pass it on to logic.stundentsList. But how to display it also in GUI as a JList?
答案1
得分: 3
- 创建一个要显示的对象列表。
- 创建一个DefaultListModel对象来存储列表中的对象。
- 创建一个JList对象并将其模型设置为DefaultListModel。
- 将JList添加到JScrollPane以支持滚动,如果列表很长。
- 将JScrollPane添加到容器,如JFrame或JPanel,以显示JList。
英文:
- Create a list of objects that you want to display.
- Create a DefaultListModel object to store the objects in the list.
- Create a JList object and set its model to the DefaultListModel.
- Add the JList to a JScrollPane to allow for scrolling if the list is
long. - Add the JScrollPane to a container such as a JFrame or JPanel to
display the 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);
}
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。


评论