Search code examples
javaswingjscrollpanejlist

JScrollPane isn't displayed


String test[] = {"1", "2", "3", "4", "5", "6", "7", "75" };
    list = new JList(test);
    list.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
    list.setLayoutOrientation(JList.VERTICAL);
    list.setVisibleRowCount(5);
    list.setLocation(50,159);
    list.setSize(50, 100);

    JScrollPane jScrollPane1= new JScrollPane();
    jScrollPane1.setViewportView(list);

    add(jScrollPane1);

EDIT: Updated my code as you guys said. Still not working :(

So that's basically my entire code for this list. When I run the program you can see the list. But you can see only the first 5 Numbers and cannot scroll or something like that. That the first 5 numbers are shown is intended, I know.

So what do I do wrong that there is no scrollbar?

Btw, I googled for years so don't come with such an anoying answer...

Thanks for reading and helping me^^


Solution

  • try with this

    JScrollPane jScrollPane1= new JScrollPane()
    jScrollPane1.setViewportView(jList1);
    getContentPane().setLayout(null);// here u specify layout put the layout what u want
    getContentPane().add(jScrollPane1);// add to the contentPane
    jScrollPane1.setBounds(126, 63, 100, 100);// here we set coordinates x, y width height cause we have null layout
    pack();// Size the frame.
    

    NOTE You should always provide a layoutManager

    so then u dont have to setBounds "hardcoded"

    JScrollPane jScrollPane1= new JScrollPane()
    jScrollPane1.setViewportView(jList1);
    setLayout(new BorderLayout());
    add(jScrollPane1);// add to the frame
    pack();// Size the frame.
    

    Also a good practice is to use a top level container to add to a Frame for example, u could use a JPanel

    setLayout(new BorderLayout());
    JPanel panel = new JPanel();
    panel.setLayout(new VerticalLayout()); // this layout is in swingx package
    JScrollPane jScrollPane1= new JScrollPane()
    jScrollPane1.setViewportView(jList1);
    setLayout(new BorderLayout());
    panel.add(jScrollPane1);// add to the frame
    add(panel);
    pack();// Size the frame.