Search code examples
javaswingjlist

create JList without using collections


I have a problem with my exercise for university. I need to create a JList and put there a few elements (just a simple text) without using any collections nor arrays. It's quite silly because a JList is usually initialized with DefaultListModel (it's a collection too), but in this case I'm not allowed to use it. I tried to put a JLabel object in a parametrized constructor of JList but it doesn't work. Do anyone of you have an idea how to deal with it? Much thanks for help in advance.

My code so far:

JFrame jFrame = new JFrame("title");
JList<String> jList = new JList<>();
jList.add(new JLabel("label1"));
jFrame.add(jList);
jFrame.setSize(500, 500);
jFrame.setVisible(true);

Solution

  • When I correct understand your academic, you simply need to create a list model, which simply returns the constant value or can calculate row value using a formula.

    Here is my suggestion for you.

    import javax.swing.AbstractListModel;
    import javax.swing.JFrame;
    import javax.swing.JList;
    import javax.swing.JScrollPane;
    import javax.swing.SwingUtilities;
    import javax.swing.WindowConstants;
    
    public class SimpleListExample implements Runnable {
    
    
        public static void main(String[] args) {
            SwingUtilities.invokeLater(new SimpleListExample());
        }
    
        @Override
        public void run() {
            JList<String> list = new JList<>(new SimpleListModel());
            JFrame frame = new JFrame("List example");
            frame.add(new JScrollPane(list));
            frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
            frame.setSize(350, 200);
            frame.setLocationRelativeTo(null);
            frame.setVisible(true);
        }
    
        @SuppressWarnings("serial")
        private static class SimpleListModel extends AbstractListModel<String> {
    
            @Override
            public int getSize() {
                return 20;
            }
    
            @Override
            public String getElementAt(int index) {
                // Generate constant value with the row index ;)
                return "It's row number: " + (index + 1);
            }
        }
    }