Can you set a permanent size for a JPanel inside of a JFrame?

39,537

Solution 1

GridBagLayout is what you really want to use. The GridLayout will force the same size for each component in the layout no matter what size constraints you put on them. GridBagLayout is a lot more powerful and a lot more complicated. Study up on the API page for it. Using GridBagLayout, the components won't fill the whole grid space if you don't want them to and can even stay the size that you ask it to be. To keep a component's size from changing, I would set all three available size constraints:

water.setPreferredSize(new Dimension(20, 20));
water.setMinimumSize(new Dimension(20, 20));
water.setMaximumSize(new Dimension(20, 20));

For your buttons, I would definitely use an inner panel as Bryan mentions. You could use either a GridLayout like he suggests or a FlowLayout if you don't want all the buttons to be the same size. Add all your buttons to that inner panel instead of the main one.

Solution 2

If you can setResizeable( false ) on the top level frame you can then set your layout manager to null and hard code each location and size via setBounds. This is how I would do it (contingent on resizing of course).

Share:
39,537
Tomek
Author by

Tomek

Updated on September 25, 2020

Comments

  • Tomek
    Tomek almost 4 years

    My current problem is that I have a JFrame with a 2x2 GridLayout. And inside one of the squares, I have a JPanel that is to display a grid. I am having a field day with the java swing library... take a look

    Image

    Java is automatically expanding each JLabel to fit the screen. I want it to just be those blue squares (water) and the black border and not that gray space. Is there a way I can just set the size of that JPanel permanently so that I don't have to go through changing the size of the JFrame a million times before I get the exact dimension so that the gray space disappears?

    I also would like to set the size of those buttons so they are not so huge (BorderLayout is being used for the buttons and TextField)