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();
}
}
- 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.
- 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!