0

My JFrame has a central Panel which has more width and height than screen Dimensions and I want this central Panel to be displayed inside JScrollPane , Now the problem is in vertical scrollbar which is not appearing . JScrollPane is showing only its horizontal position not vertical. Following is the code of my JFrame.

import java.awt.*;
import javax.swing.*;

public class TestScroll extends JFrame {

    public TestScroll() {
        Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();

        this.setSize(screenSize.width,screenSize.height);
        getContentPane().setLayout(new BorderLayout());
        JPanel centerPanel=new JPanel(new BorderLayout());
        centerPanel.setSize(screenSize.width+50,screenSize.height+50);//I want centralPanel to be of more width and height so to test JScollPane


        JPanel northPanel = new JPanel();
        Dimension d1=centerPanel.getSize();
        northPanel.setPreferredSize(new Dimension(d1.width,d1.height/3));
        northPanel.setBackground(Color.BLACK);
        centerPanel.add(northPanel, BorderLayout.NORTH);

        JPanel innerPanel = new JPanel();
        //Dimension d1=centerPanel.getSize();
        //panel2.setPreferredSize(new Dimension(d1.width,d1.height/2));
         innerPanel.setBackground(Color.ORANGE);
        centerPanel.add(innerPanel, BorderLayout.CENTER);

        JScrollPane pane=new JScrollPane(centerPanel);
        pane.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED);
        pane.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED);

        getContentPane().add(pane, BorderLayout.CENTER);
        this.setVisible(true);

    }

    public static void main(String[] args) {

new TestScroll();
    }

}

Kindly help me to display vertical ScrollBar..

2 Answers2

2

In Swing, you have several ways for component layout: do everything manually or use a LayoutManager.

Calling setSize() works only work when you're not using a LayoutManager inside your container. The panel basically adjusts to the size of its container (your window) and does not have the size you desire, because it is not the setSize() method managing the size of your component, but your BorderLayout manager.

However, If you fill your panel with content which is bigger than the screen size, the scroll bars will appear.

You can override getPreferredSize() of your component so it returns the desired dimension, as shown here and here.

If you wish to show scrollbars even when the component in not bigger than the JScrollPane, you can set it liek this:

pane.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS);
Community
  • 1
  • 1
Smajl
  • 7,555
  • 29
  • 108
  • 179
0

you can use this innerPanel.setPreferredSize(new Dimension(d1.width,2*(d1.height/3)));to see the vertical scroll bar.

Krishna Kant
  • 105
  • 9