Create JList and always display the scroll bar in Java?

Java 8Object Oriented ProgrammingProgramming

To always display the scroll bar in a JList, use the properties HORIZONTAL_SCROLLBAR_ALWAYS and VERTICAL_SCROLLBAR_ALWAYS:

JList list = new JList(sports);
JScrollPane scrollPane = new JScrollPane(list);
scrollPane.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS);
scrollPane.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);

The following is an example to create JList and display the scroll bar:

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);
      scrollPane.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS);
      scrollPane.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
      frame.add(scrollPane);
      frame.getRootPane().setWindowDecorationStyle(JRootPane.PLAIN_DIALOG);
      frame.setSize(400,100);
      frame.setVisible(true);
   }
}

Output

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

Advertisements