Friday, July 31, 2009

How to keep the aspect ratio on a Java GUI window?

I'm coding up a GUI in java using swing and java2D and would like all the components within the window to expand or shrink down in relation to the size of the window. What's the best way to do this?

How to keep the aspect ratio on a Java GUI window?
Use an appropriate Layout such as GridBagLayout or SpringLayout





example:


Container contentPane = jframe.getContentPane();


contentPane.setLayout ( new GridBagLayout() );





// x y w h wtx wty anchor fill T L B R padx pady


contentPane.add( myPanel, new GridBagConstraints( 0, 0, 1, 1, 0.0, 0.0, GridBagConstraints.WEST, GridBagConstraints.BOTH, new Insets( 10, 10, 10, 5 ), 0, 0 ) );


contentPane.add( myPanel2, new GridBagConstraints( 1, 0, 1, 1, 0.0, 0.0, GridBagConstraints.EAST, GridBagConstraints.BOTH, new Insets( 10, 5, 10, 10 ), 0, 0 ) );





I just read your additional note. You also would like labels, etc. to be expanded as well. Hmm, I don't know of anything that will do this automagically for you. You could extend some of the components to take hints from the layout and resize appropriately. For instance, you may choose to enlarge the font when you determine more whitespace is available due to a window resize. I'm not aware of existing component that will do this for labels. Proportional fonts are a bit tricky to get this right. Actually, if memory serves me, I once did something similar. It was like "trial-and-error" programmatically. Off screen, I would draw the character string in the estimated font size and redraw down until it fit in the allotted space with the desired margins. Sure seems like a lot of trouble to get these dynamic labels to look good!


No comments:

Post a Comment