Search code examples
javaswingjpaneljscrollpanegridbaglayout

Second row of gridbaglayout scrolling out of container


I am trying to achieve a layout similar to that of a carousel. It needs to have images added horizontally with a checkbox field in the second row. I have a panel within a jscrollpane and individual images are added to the panel as labels. Please see screen shot.

screenshot
enter image description here

When I scroll the pane , the first row containing the images stays well within the panel..but if you notice the second row of checkboxes , it scrolls out of the panel. Here is the code ...

JLabel lab1=new JLabel();
for (int ii=0; ii<imageFiles.length; ii++) {
       GridBagConstraints constraint = new GridBagConstraints();  
        lab1 = new BufferedImage(w,h,BufferedImage.TYPE_INT_RGB);

        constraint.gridx = ii;
        constraint.gridy =0;  
        jPanel9.add(lab1,constraint);
    }
    for (int ii=0; ii<imageFiles.length; ii++) {
        GridBagConstraints constraint1 = new GridBagConstraints();         
        constraint1.anchor = GridBagConstraints.SOUTH;           
        chkbox = new Checkbox("asdasdada");
        constraint1.gridx = ii;
        constraint1.gridy =1;

        jPanel9.add(chkbox, constraint1);
      } 

Not sure what is wrong..Any help is much appreciated..Thanks..


Solution

  • The problem is that you are mixing AWT components (heavyweight) with Swing components (lightweight). I have 2 recommendations:

    • Don't mix heavyweight and lightweight components
    • Try to use lightweight components as much as possible

    So in your code, replace Checkbox by JCheckbox and it should work just fine.