Search code examples
javaswinguser-interfacejscrollpanejlist

Add a JScrollPane to a JList


I have the following code: Main:

package PackageMain;

import java.awt.EventQueue;

import javax.swing.JFrame;
import javax.swing.WindowConstants;

public class Main {

public static JFrame frame = new JFrame("Window");
public static PanelOne p1;
public static PanelTwo p2;

public static void main(String[] args) {
    EventQueue.invokeLater(new Runnable() {
        public void run() {
            try {
                frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
                frame.setBounds(100, 100, 800, 600);
                p1 = new PanelOne();
                p2 = new  PanelTwo();
                frame.setVisible(true);
            } catch(Exception e){

            }
        }
    });
}

And class 2:

package PackageMain;

import java.awt.Color; 
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;

import javax.swing.DefaultListModel;
import javax.swing.JLabel;
import javax.swing.JList;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.ScrollPaneConstants;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;

public class PanelOne{

public PanelOne(){
    loadScreen();
}

public void loadScreen(){
    JPanel p1 = new JPanel();
    DefaultListModel model = new DefaultListModel<String>();
    JList list = new JList<String>(model);
    //
    JScrollPane scroll = new JScrollPane(list);
    list.setPreferredSize(null);
          scroll.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS;
    scroll.setViewportView(list);
    //
    list.addListSelectionListener(new ListSelectionListener() {
        public void valueChanged(ListSelectionEvent arg0) { 
            System.out.println("You selected " + list.getSelectedValue());
        }
    });
    p1.add(list);
    Main.frame.add(p1);
    Main.frame.revalidate();
    Main.frame.repaint();
    for (int i = 0; i < 100; i++){
        model.addElement("test");
    }
}

I've tried a bunch of stuff to get the JScrollPane to appear on the JList, but it doesn't want to. My best guess is that the model is screwing things up, but this is a simplified version, and the model needs to be there.


Solution

  • JScrollPane scroll = new JScrollPane(list);
    

    You add the JList to the JScrollPane which is correct.

    p1.add(list);
    

    But then you add the JList to the JPanel, which is incorrect. A component can only have a single parent, so theJListis removed from theJScrollPane`.

    You need to add the JScrollPane to the JPanel:

    p1.add( scroll );