Param-Ganak
Param-Ganak

Reputation: 5875

Why it shows scrollbar to JScrollPane when we use setPreferredSize for the JPanel which is added to JScrollPane

Please see the following block of code

import java.awt.Color;
import java.awt.Dimension;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JSplitPane;
public class test extends JFrame {
    public test(){

    this.setBounds(0,0,300,700);

    JPanel pnltemp= new JPanel();

    //pnltemp.setBounds(0,0,400,1000);
    pnltemp.setPreferredSize(new Dimension(400,1000));

    JScrollPane scrtemp= new JScrollPane();


    scrtemp.getViewport().add(pnltemp);
    this.getContentPane().add(scrtemp);

    this.getContentPane().add(scrtemp);
    this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    this.setVisible(true);

}

public static void main(String args[]){
    new test();

}
}
  1. When we run the above code by commenting "pnltemp.setBounds(0,0,400,1000);" and replacing it with "pnltemp.setPreferredSize(new Dimension(400,1000));" the window shows horizontal and vertical scrollbars. but when we run the same programm by commenting "pnltemp.setPreferredSize(new Dimension(400,1000));" and replacing it wiht "pnltemp.setBounds(0,0,400,1000)" the window does not shows horizontal and vertical scrollbars.

why same program behaves differently by changing the setBounds and setPreferredSize method; as these two methods are looks same in behaviour.

Or is it something like this that when we are using the JScrollPane to get the Scrollbar we must use the setPreferredSize(); method for the componant that we are going to add in JScrollPane.

  1. My second question is when we add pnltemp to scrtemp i.e. the JPanel is added to JScrollPane directly then its not gives an error means when we say

scrtemp.add(pnltemp);

it does not give any error but it also does not show the pnltemp and scrollbar in scrtemp. but when we type scrtemp.getViewPort.add(pnltemp);

it does not give any error but it also shows the pnltemp and scrollbar in scrtemp.

I checked this by assigning the background color to JPanel and JScrollPane.

Can anybody explin this?

Thank You!

Upvotes: 1

Views: 1438

Answers (1)

StanislavL
StanislavL

Reputation: 57381

From the JScrollPane JavaDocs.

By default JScrollPane uses ScrollPaneLayout to handle the layout of its child Components. ScrollPaneLayout determines the size to make the viewport view in one of two ways:

  1. If the view implements Scrollable a combination of getPreferredScrollableViewportSize, getScrollableTracksViewportWidth and getScrollableTracksViewportHeight is used, otherwise
  2. getPreferredSize is used.

Upvotes: 3

Related Questions