I have a JList that I need to Place inside a scroll Pane because I am getting the JList from the database and the values can increase greatly. I need to be able to scroll th
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);
}
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);
}
});
}
}