简体   繁体   中英

Java swing GridLayout adjusting cellsize

After starting a JPanel using GridLayout(4,4) i insert a JLabel (and attach an imageicon to it) inside every grid cell with size of (150,150).

when i resize the JLabel to size (100,100) the image get cropped (which is perfectly fine by me), but i get a wierd looking grid (imaged added at the end).

if this helps: i dont actually resize the window, i just need to make sure the the size of the JLabel is set to (100,100) always, no metter what is the original image size.

before: http://postimg.org/image/iolyeb8e7/

after: http://postimg.org/image/5j6g87ein/

thanks

Unfortunately you did not say what you expect the grid to look like. I assume you don't want the cells to be so far apart from each other.

The GridLayout documentation states that...

The container is divided into equal-sized rectangles, and one component is placed in each rectangle.

If you shrink the size of each JLabel (ie the components in each of those rectangles) you just do that. You shrink the size of the component, not that of the rectangle. The grid does not care if the component is to small to fill the whole rectangle. At the moment you add the component to the grid 1 , the grid tries to set the components size to best fit the available space. But if you later change the labels size, the grid does not care.

What you probably want is to change the size of the whole grid: If you set the grids size to 400 by 400 it should evenly divide it to all 4 rows and 4 columns, so you get rectangles of size 100 by 100. All labels should automatically be sized accordingly.


1 Probably it is not exactly while adding the labels but while validating the container , but I don't know all the internal details about how and when layouts do there magic.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM