Reputation: 36742
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
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
Edit :
Now What I feel the problem is with the BoxLayout
of the PhotoBox
.
Upvotes: 4
Views: 268
Reputation: 8473
Please check the image's height because the layout is correct AFAICS, there is nothing else. :D
Upvotes: 2
Reputation: 23629
GridLayout is going to fill the available space it is placed in. So the container that title
is added to must actually have that height available and Gridlayout is filling it.
Three options exist for a fix:
Upvotes: 2
Reputation: 347204
This is the nature of GridLayout
. It takes the available space and divides it equally amongst all the components. Take a look at How to Use GridLayout.
How to fix will come down to eaxctly what you want. You could use a GridBagLayout
, but you'll become responsible for supplying the constraints that determine the locations of each component.
You could also take a look at Wrap Layout by Rob Camick. This is a FlowLayout
as it probably should have a done, as it provides line wrapping for the components.
You should take a look at A Visual Guide to Layout Managers for more ideas.
You may also consider taking a look at MigLayout
Upvotes: 2