How to add JList to Scroll pane in Java?

Java 8Object Oriented ProgrammingProgramming

To add JList to Scroll pane in Java, use JScrollPane:

JList list = new JList(sports);
JScrollPane scrollPane = new JScrollPane(list);

After that set it to Container:

Container contentPane = frame.getContentPane();
contentPane.add(scrollPane, BorderLayout.CENTER);

The following is an example to add JList to Scroll pane:

Example

package my;
import java.awt.event.*;
import java.awt.*;
import javax.swing.*;
class SwingDemo extends JFrame {
   static JFrame frame;
   static JList list;
   public static void main(String[] args) {
      frame = new JFrame("JList Demo");
      frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
      String sports[]= {"Tennis","Archery","Football","Fencing","Cricket","Squash","Hockey","Rugby"};
      list = new JList(sports);
      JScrollPane scrollPane = new JScrollPane(list);
      Container contentPane = frame.getContentPane();
      contentPane.add(scrollPane, BorderLayout.CENTER);
      frame.setSize(400,100);
      frame.setVisible(true);
   }
}

The output is as follows. As you can see ScrollPane is visible for the items:

Output

raja
Updated on 30-Jul-2019 22:30:26

Advertisements