Search code examples
javaswingresizelayout-managerjcomponent

How to make a swing component's bounds fixed


I have a JPanel to which I have added a few components (checkbox, combo etc.). I have noticed that, when the frame is maximized, the bounds of components also move or shift to the right. Then, on restore the components are shifted back to the original position.

On 21 and above inch monitor, the components shift really makes a difference as you can see the components move far right.

We are using customized layout manager which implements java.awt.LayoutManager2. The class content is quiet huge, so will point to the areas which determine the bounds for the components.

protected int hMargin = 0;
..
Insets insets = target.getInsets();
Dimension size = target.getSize();

int  x = (size.width - insets.left - insets.right - 15 * hMargin);

And from the frame which calls the layout and add the components as shown below:

JPanel  pl = new JPanel(new OurLayout(this))
//add the component to panel
pl.add(checkBox);
..

At the point where we decide x, I want to add a line to prevent the components from shifting when the frame on which the calling panel is added is maximized.

Can anyone suggest any ideas on how to achieve this? example code will be well appreciated.


Solution

  • Thanks to Thomas and camickr for their recommendations, I have achieved a solution using the line of syntaxes below.

          size=c.getMinimumSize();
          int dist =(size.width - insets.left - insets.right);
          int move = ((dist > 32) ? 35 : 38);
          x = (dist + move * hMargin);
    

    Again thanks to all for the recommendations.