Search code examples
javaswingjpanelgrid-layout

Unable to set BoxLayout(JPanel) correctly in GridLayout/FlowLayout


I have a panel with the below code

public class PhotoBox extends JPanel {


    private JLabel photoIcon;
    private JLabel photoName;
    private JLabel print;
    private ImageHelper imageHelper;


    public PhotoBox(File file, JLabel print) throws IOException {

        imageHelper = new ImageHelper();
        this.photoIcon =  new JLabel();
        this.photoIcon.setIcon(imageHelper.createThumbnails(file));
        this.photoIcon.setMaximumSize(new Dimension(200, 150));
        this.photoIcon.setAlignmentX(Component.CENTER_ALIGNMENT);

        this.photoName = new JLabel();
        photoName.setText((file.getName().length()) > 20 ? file.getName().substring(0,10)+".." : file.getName());
        this.photoName.setAlignmentX(Component.CENTER_ALIGNMENT);


        this.print = new JLabel();
        this.print.setText(print.getText());
        this.print.setAlignmentX(Component.CENTER_ALIGNMENT);

        setLayout(new BoxLayout(this , BoxLayout.Y_AXIS));
        setBorder(BorderFactory.createLineBorder(Color.black));
        //setPreferredSize(new Dimension(200,150));

        add(this.photoIcon);
        add(this.photoName);
        add(this.print);
    }
}

Now I am adding a list of such panel into another JPanel with has GridLayout

JPanel tile = new JPanel();
GridLayout layout = new GridLayout(0,4);
tile.setLayout(layout);
PhotoBox vBox = new PhotoBox(file,filePrints.get(file.getName()));
tile.add(vBox);

But what I finally get is something like this

GridLayout Gap error

I don't understand why is that extra space being taken by all my PhotoBox objects. I want the images to be close together. Not to forget, I have already tried PrefSize() and it doesn't work.

Using WrapLayout/FlowLayout

enter image description here

Edit :

Now What I feel the problem is with the BoxLayout of the PhotoBox.


Solution

  • Please check the image's height because the layout is correct AFAICS, there is nothing else. :D