Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Equivalent of Swing's pack in C#

I am developing a quick app in C#. One thing that I want to do is the equivalent of Swing's (java) pack(). This is a call that allows me to say to a form (Frame in Java), resize yourself to the size of the sum of the components within yourself.

I have searched and searched (the components change dynamically so I cannot simply hardcode the form to the right size) but I cannot find the equivalent method in C#.

Does anyone know what it is called?

like image 852
Neil Benn Avatar asked Jul 16 '09 18:07

Neil Benn


People also ask

What is Frame Pack ()?

The pack() method is defined in Window class in Java and it sizes the frame so that all its contents are at or above their preferred sizes. An alternative to the pack() method is to establish a frame size explicitly by calling the setSize() or setBounds() methods.

Which is better JavaFX or Swing?

In short, Swing and JavaFX are both GUI toolkits for Java programs. Swing is the old standard toolkit that features a bigger library of GUI elements and mature IDE support. JavaFX is the newer standard with a smaller library, more consistent updates, and consistent MVC support.

Is Swing still used in Java 2022?

Swing and AWT will continue to be supported on Java SE 8 through at least March 2025, and on Java SE 11 (18.9 LTS) through at least September 2026.


2 Answers

You don't even need write code in order to 'pack' the form. In the forms designer, set the form's AutoSize property to true, and set the AutoSizeMode property to GrowAndShrink, repeat this for any controls on the form which may also change size.

And voila!

At runtime (only), the form will dynamically resize itself to accommodate all the controls. If you want it to keep a little distance from the controls so that the controls won't 'stick' to the edges, you can set the Padding property (I'd recommend at least a value of 12,12,12,12).

like image 89
Allon Guralnek Avatar answered Nov 04 '22 02:11

Allon Guralnek


Also in xaml:

<Window SizeToContent="WidthAndHeight" />
like image 43
Sam Avatar answered Nov 04 '22 04:11

Sam