Tutorialspoint

1 Answer
Ankith Reddy

To set scrollbars to never appear, use the JScrollPane.HORIZONTAL_SCROLLBAR_NEVER and JScrollPane.VERTICAL_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, set the scrollbars to never appear:

scrollPane.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);
scrollPane.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_NEVER);

The following is an example to set scrollbars to never appear:

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("One");
      JButton button2 = new JButton("Two");
      JButton button3 = new JButton("Three");
      JButton button4 = new JButton("Four");
      JButton button5 = new JButton("Five");
      JButton button6 = new JButton("Six");
      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);
      scrollPane.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_NEVER);
      frame.add(scrollPane, BorderLayout.CENTER);
      frame.setSize(550, 250);
      frame.setVisible(true);
   }
}

This will produce the following output. Here, the preferred size of the box is bigger enough to display the scroller, but it won’t be visible since we have disabled horizontal and vertical scrollbar and set it to NEVER:

Advertisements

We use cookies to provide and improve our services. By using our site, you consent to our Cookies Policy.