Create JList and always display the scroll bar in Java?



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

Updated on: 2019-07-30T22:30:26+05:30

528 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements