How to disable only the horizontal scrollbar in Java?



To disable only the horizontal scrollbar in Java, use the JScrollPane.HORIZONTAL_SCROLLBAR_NEVER. Let’s say you created a Box with some button components. Now, create a JScrollPane −

JScrollPane scrollPane = new JScrollPane();

Set the Viewport view as Box −

scrollPane.setViewportView(box);

Now, disable the horizontal scrollbar −

scrollPane.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);

The following is an example to disable only the horizontal scrollbar −

Example

package my; import java.awt.BorderLayout; import java.awt.Dimension; import javax.swing.Box; import javax.swing.JButton; import javax.swing.JFrame; import javax.swing.JScrollPane; public class SwingDemo {    public static void main(String args[]) {       JFrame frame = new JFrame("Demo");       frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);       JButton button1 = new JButton("Tutorials");       JButton button2 = new JButton("Quiz");       JButton button3 = new JButton("Questions and Answers");       JButton button4 = new JButton("Videos");       JButton button5 = new JButton("Tools");       JButton button6 = new JButton("Online Compiler");       Box box = Box.createVerticalBox();       box.setPreferredSize(new Dimension(900,900));       box.add(button1);       box.add(button2);       box.add(button3);       box.add(button4);       box.add(button5);       box.add(button6);       JScrollPane scrollPane = new JScrollPane();       scrollPane.setViewportView(box);       scrollPane.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);       frame.add(scrollPane, BorderLayout.CENTER);       frame.setSize(550, 250);       frame.setVisible(true);    } }

This will produce the following output −

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

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements