tags:

views:

51

answers:

3

Is it by using the setLocation or by layout? can you give me some advice how can i easy place a Swing component in a frame?

A: 

The recommended approach is to use Layout Managers to position components in a container. The advantage is that the layout managers will provide the functionality of resizing or repositioning components that are next to each other as the container is resized.

Programming all that behaviour yourself is not necessary.

Vincent Ramdhanie
+2  A: 

See http://java.sun.com/docs/books/tutorial/uiswing/layout/none.html for absolute positioning in Swing :) However, mostly you would avoid this and use proper layout managers. For this, I suggest on the use of MigLayout which is an incredibly powerful layout manager (easy to specify layouts directly in code), or with the Netbeans UI designer, Mattise which uses GridBagLayout and writes the .java files automatically with insertion points for your own code, for responding to UI events and such.

alt text

MigLayout example:

 JPanel p = new JPanel(new MigLayout("", "[right]"));

 p.add(new JLabel("General"),  "split, span, gaptop 10");
 p.add(new JSeparator(),       "growx, wrap, gaptop 10");

 p.add(new JLabel("Company"),  "gap 10");
 p.add(new JTextField(""),     "span, growx");
 p.add(new JLabel("Contact"),  "gap 10");
 p.add(new JTextField(""),     "span, growx, wrap");

 p.add(new JLabel("Propeller"),"split, span, gaptop 10");
 p.add(new JSeparator(),       "growx, wrap, gaptop 10");

 p.add(new JLabel("PTI/kW"),   "gap 10");
 p.add(new JTextField(10),     "");
 p.add(new JLabel("Power/kW"), "gap 10");
 p.add(new JTextField(10),     "wrap");
 p.add(new JLabel("R/mm"),     "gap 10");
 p.add(new JTextField(10),     "wrap");
 p.add(new JLabel("D/mm"),     "gap 10");
 p.add(new JTextField(10));
Chris Dennett
A: 

Definitely use a layout manager, since then you're flexible enough to handle things like varying layouts depending on platform (affects the sizes of buttons) and font size. The latter is important if you're wanting to build accessible applications as some users have problems seeing small text and so apply a global multiplier to the font sizes. An added bonus is that you can then also cope with the overall window being resized easily.

But avoid the GridBagLayout. It's powerful, but requires a lot of work to make it not suck, so much so that it's easier to write your own specialist layout from scratch…

Donal Fellows