Hello, I'm trying to create a chess program that uses a JPanel with an 8 by 8 grid layout with 64 jlabels with icons. However, I don't want the icons to be distorted if the user resizes the window in such a way that makes the panel not square. Is there any way I could create a JPanel that maintains a square aspect ratio when it is resized?
GridLayout will resize the JLabel to fill all available space within it's cell, but the ImageIcon dimensions would be fixed. So, it shouldn't be an issue. If the icon was 25 x 25, and the JLabel dimensions was 50 x 25, 12.5 pixels of padding would appear on each side of the icon. Please see my attached example output that I drummed up quickly using:
Maybe I didn't phrase my question correctly, but your pictures are exactly what I'm trying to avoid. I would like the board to be a square no matter what size it, even if this means leaving empty space below or to the side of it. I don't ever want any space in between the board squares, I just want all of them to get bigger or smaller when the window is resized. And I have figured out how to get the pictures themselves to maintain their aspect ratio within gridlayout, but I'm trying to avoid the shifting of the space between the rows and columns of the board by creating a jpanel to house all the squares in that stays square no matter how it is resized.
Ok, I modified and combined the example code with mine, and now the board successfully stays square. However, I would like the board to be in the top left of the main panel at all times, but the example has the board constantly centered (which the author says is very important). When I remove the centering of the chessboard within the main panel, sure enough, the old resizing behavior takes over. Anyone know how to fix this? I thought components in java were positioned based on their top left corner, not the center, so I didn't think position would matter to making the board resize correctly, but apparently it does. Here is my code right now:
I've tried changing the gridbag constraints, but this doesn't seem to affect anything. I think the problem is this set of lines:
When I change the layout of the whole thing to anything other than BorderLayout, or when I change the third line above to anything other than BorderLayout.CENTER, the whole board dissapears. Do you know why this is?
And to Rob, I did try adding the panel as the first (and only) component) in a flow layout, but then the board promptly dissapeared, and I'm not sure (it also dissapears for any layout other than BorderLayout, and any other BorderLayout specification than BorderLayout.CENTER). Here is what I tried:
Awesome, that worked thank you! I'm not sure I understand what I've done exactly though-so many panels inside panels inside panels with different layouts. So I'll have to go back over the code to figure out what its doing now. Here is the final code:
My favorite is a chocolate cupcake with white frosting and tiny ad sprinkles.