How to display a list of objects as a JList in java swing?

1.2k views Asked by At

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

There are 1 answers

0
SaidTheHypocrite On
  1. Create a list of objects that you want to display.
  2. Create a DefaultListModel object to store the objects in the list.
  3. Create a JList object and set its model to the DefaultListModel.
  4. Add the JList to a JScrollPane to allow for scrolling if the list is long.
  5. 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);
    }
}