Search code examples
javaswinglayout-managernull-layout-manager

JScrollPane not working in null layout


  import javax.swing.JCheckBox;
  import javax.swing.JFrame;
  import javax.swing.JLabel;
  import javax.swing.JPanel;
  import javax.swing.JScrollPane;

public class ScrollJPanelDemo extends JFrame {
   public ScrollJPanelDemo(){
    setSize(480, 200);
    setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

    JLabel label = new JLabel("Select one or more options : ");
    JCheckBox jcb1 = new JCheckBox("Chandigarh");
    JCheckBox jcb2 = new JCheckBox("Mohali");
    JCheckBox jcb3 = new JCheckBox("Delhi");
    JCheckBox jcb4 = new JCheckBox("Noida");
    JCheckBox jcb5 = new JCheckBox("Mumbai");
    JCheckBox jcb6 = new JCheckBox("Kolkata");

    //creating JPanel to hold the checkboxes
    JPanel jpnl = new JPanel();
    jpnl.setLayout(null);
    jpnl.setOpaque(true);
    jcb1.setBounds(0,0,100,40);
            jcb2.setBounds(0,60,100,40);
            jcb3.setBounds(0,120,100,40);
            jcb4.setBounds(0,180,100,40);
            jcb5.setBounds(0,240,100,40);
            jcb6.setBounds(0,300,100,40);
    //adding check boxes and label to the JPanel
    jpnl.add(label);
    jpnl.add(jcb1);
    jpnl.add(jcb2);
    jpnl.add(jcb3);
    jpnl.add(jcb4);
    jpnl.add(jcb5);
    jpnl.add(jcb6);

    //creating the scroll pane that will scroll the panel.
    JScrollPane jscrlPane = new JScrollPane(jpnl);
    jscrlPane.setBounds(0,0,300,300);



        jscrlPane.setHorizontalScrollBarPolicy
       (JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS) ;
   jscrlPane.setVerticalScrollBarPolicy
   (JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);

    //adding that scroll pane to the frame.
    getContentPane().add(jscrlPane);
    setVisible(true);
  }

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

 }

I'm new in Java Swing and try to use of Scroll pane on my Java code, but it's not working. The Scroll Pane is add on the frame in vertical direction but not worked.


Solution

  • You should create your own panel that extends JPanel containing all checkboxes and in this panel override getPreferredSize() method like:

    @Override
    public Dimension getPreferredSize()
    {
        return new Dimension( 300,300 );
    }
    

    and use it in your code:

    ...
    
    // creating the scroll pane that will scroll the panel.
    JScrollPane jscrlPane = new JScrollPane( new MyPanelWithCheckboxes() );
    jscrlPane.setBounds( 0, 0, 300, 300 );
    ...