Home » Java » java – My panel won't scroll and my scrollpane does not have a slider-Exceptionshub

java – My panel won't scroll and my scrollpane does not have a slider-Exceptionshub

Posted by: admin February 25, 2020 Leave a comment

Questions:

I have tried all these but my scrollpane won’t scroll and it does not have a slider in it, the scroll bar displays but it has no slider in it, i have set autoscrolls and focus traveral policy but still i get nothing, please what am i doing wrong?

 JFrame frame = new JFrame("Web Dev Portal v1.0");
    frame.setResizable(true); 
    frame.setBackground(SystemColor.control); 
     frame.setSize(1050, 2000); 
      frame.setLocation(70, 70);
      frame.setLayout(new BorderLayout());
      frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
      JPanel p2 = new JPanel(); 
       p2.setBackground(SystemColor.control); 
        p2.setLayout(null);
        //creating the scrollpane object and adding the panel into it
      JScrollPane pane = new JScrollPane(p2, ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS, ScrollPaneConstants.HORIZONTAL_SCROLLBAR_AS_NEEDED);
      pane.setFocusTraversalPolicyProvider(true);
      pane.setAutoscrolls(true); 
      //setting the size of the pane
      pane.setPreferredSize(new Dimension(1202, 2500)); 
       //adding the scrollpane to frame
      frame.setContentPane(pane);
            SwingUtilities.invokeLater(new Runnable(){
          @Override
           public void run(){
            frame.setVisible(true);  
          }  
How to&Answers:

In order to show the scroll view should contain component which is bigger than the scroll pane.

Add following code after ‘pane.setPreferredSize(new Dimension(1202, 2500));’

JPanel jp = new JPanel();
jp.setPreferredSize(new Dimension(1500,3000));
pane.getViewport().add(jp);