Add a Jlist to a JScrollPane

折月煮酒 提交于 2019-12-01 01:01:30

The list is already contained inside the scrollpane, so you must not add the list to the main panel. Only the scroll pane.

Another thing you're doing wrong is not using a layout manager, and setting the bounds and sizes of your components. Don't do that. Let the layout manager position and size the components for you.

And finally, you shouldn't use Swing components from the main thread. Only in the event dispatch thread.

Here's a modified version of your code that works fine. I removed the background colors, as this should be handled by the L&F:

public class Checkboxlistener extends JFrame {

    private JPanel jpAcc = new JPanel();
    private JList<String> checkBoxesJList;

    Checkboxlistener() {
        jpAcc.setLayout(new BorderLayout());
        String labels[] = { "A", "B", "C", "D", "E", "F", "G", "H", "I", "J" };
        checkBoxesJList = new JList<String>(labels);

        checkBoxesJList.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
        JScrollPane scrollPane = new JScrollPane(checkBoxesJList);

        jpAcc.add(scrollPane);

        getContentPane().add(jpAcc);
        pack();
    }

    public static void main(String args[]) {
        SwingUtilities.invokeLater(new Runnable() {

            @Override
            public void run() {
                Checkboxlistener cbl = new Checkboxlistener();
                cbl.setVisible(true);
            }
        });
    }
}
Sugat Shivsharan

As mentioned, the list is already added to JScrollPane, hence need not be added again. Also, for scroll to work, it needs to define the list method setVisibleRowCount(int). I have modified the code above in CheckBoxListener method to make it work.

Checkboxlistener() 
{   
    setSize(1300, 600);

    String labels[] = {"A", "B", "C", "D", "E", "F", "G", "H", "I", "J"};
    checkBoxesJList = new JList(labels);
    checkBoxesJList.setBounds(10, 30, 80, 600);
    checkBoxesJList.setBackground(Color.LIGHT_GRAY);
    checkBoxesJList.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);

    checkBoxesJList.setVisibleRowCount(5);

    JScrollPane scrollPane = new JScrollPane(checkBoxesJList);  

    jpAcc.add(scrollPane);

    add(jpAcc);

    setVisible(true);

}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!