Which Layout Manager do you use? - java

What java GUI layout manager does everyone use? Lately, I have been using MigLayout, which has some powerful component controls. Just wanted to see what other developers are using other than the standard JDK ones.

MiGLayout is the GUI layout manager which is widely used by Java Developers.

GridBagLayout is usable. Once you get used to using it, it works great. I think the standard JDK layout managers are pretty powerful on their own. Plus, you get to minimize dependency on 3rd party libraries.

MiG and FormLayout (JGoodies) are both excellent for manual layout (And almost all layout eventually becomes manual). My biggest piece of advice is to design your views so that you can completely rip out the layout and re-implement it without impacting your application (good separation of view and controller is key here).
Definitely take a look at JGoodie's PresentationModel approach for implementing 'dumb' views. I use this technique with a GUI builder (I use GroupLayout with the Jigloo GUI builder plugin) for tossing off quick prototypes. After 3 or 4 iterations, that usually goes out the window and we do a re-implement using MiG or FormLayout.
EDIT: Since I wrote this, I have moved to using MiG for all of my layouts, and I no longer use a GUI builder - it's just way too easy to lay things out using MiG.

The last Swing application I worked on used JGoodies' FormsLayout.

I use the GridBagLayout. It seems to take alot of code, but it makes very good looking layouts.
I also like to combine BorderLayout with GridBagLayout panels for great customizability.

I'm a big fan of using TableLayout instead of GridBagLayout. Everything just makes sense, whereas every time I try to use GridBagLayout it crushes my soul.

I use to go for GridBagLayout for the control, but since java1.6 I'm going to use GroupLayout Is awsome.
Here an screenshot and sample code to use it!.
alt text http://img145.imageshack.us/img145/7844/screenshot1dz8.png
private void layoutComponents(){
JPanel panel = new JPanel();
GroupLayout layout = new GroupLayout(panel);
panel.setLayout(layout);
layout.setAutoCreateGaps(true);
layout.setAutoCreateContainerGaps(true);
SequentialGroup hGroup = layout.createSequentialGroup();
JLabel nameLbl = new JLabel("Name");
JLabel countLbl = new JLabel("Amount");
JLabel dateLbl = new JLabel("Date(dd/MM/yy)");
hGroup.addGroup(layout.createParallelGroup().
addComponent(nameLbl).
addComponent(countLbl).
addComponent(dateLbl).
addComponent(go));
hGroup.addGroup(layout.createParallelGroup().
addComponent(name).
addComponent(count).
addComponent(date));
layout.setHorizontalGroup(hGroup);
SequentialGroup vGroup = layout.createSequentialGroup();
vGroup.addGroup(layout.createParallelGroup(Alignment.BASELINE).
addComponent(nameLbl).addComponent(name));
vGroup.addGroup(layout.createParallelGroup(Alignment.BASELINE).
addComponent(countLbl).addComponent(count));
vGroup.addGroup(layout.createParallelGroup(Alignment.BASELINE).
addComponent(dateLbl).addComponent(date));
vGroup.addGroup(layout.createParallelGroup(Alignment.BASELINE).
addComponent(go));
layout.setVerticalGroup(vGroup);
frame.add( panel , BorderLayout.NORTH );
frame.add( new JScrollPane( textArea ) );
}

I use DesignGridLayout for most of my panels.
For the rare panels that DesignGridLayout cannot fully handle, I use a mix of Borderlayout and DesignGridLayout.
With DesigngridLayout you can manually code your layouts with a minimum number of lines of code, that are easy to type and read:
DesignGridLayouut layout = new DesignGridLayout(myPanel);
layout.row().grid(lblFirstName).add(txfFirstName).grid(lblSurName).add(txfSurName);
layout.row().grid(lblAddress).add(txfAddress);
layout.row().center().add(btnOK, btnCancel);
Each row of the panel grid is defined by one line of code. As you can see, "drawing" your panel is quite straightforward.
In addition, I find DesignGridLayout has some unique features (such as its "smart vertical resize").

GridBagLayout is powerful but quite primitively: the code that wires up the layout is very verbose. This utility library (actual just 1 jar file containing about 10 classes) simplifies a lot of works: http://code.google.com/p/painless-gridbag/ The following snippet is quoted from the home page of that site:
PainlessGridBag gbl = new PainlessGridBag(getContentPane(), false);
gbl.row().cell(lblFirstName).cell(txtFirstName).fillX()
.cell(lblFamilyName).cell(txtFamilyName).fillX();
gbl.row().cell(lblAddress).cellXRemainder(txtAddress).fillX();
gbl.doneAndPushEverythingToTop();

As a general overview, you might find an article I wrote a loooong time ago at sun to be useful. It's not up to date with the latest layout managers, but it concentrates on effective nesting of layout managers, rather than trying to do everything with one layout.
See http://developer.java.sun.com/developer/onlineTraining/GUI/AWTLayoutMgr

I've found that for any non-trivial GUI I use multiple layouts with nested sub-panels where the main panel may have a GridBagLayout and each sub-panel (typically without a border or indication that it is a panel) uses a simpler layout where possible. Typically I'll use BorderLayout, FlowLayout, and BoxLayout for smaller, simpler sub-panels. By dividing small sections of the GUI into sub-panels and using the simplest layout possible to control that section of the GUI you can create complex, well arranged displays without too much headache from GridBagLayout's many options. Also, by grouping like display functionality into a panel, it creates more readable code.

Spring layout which was developed for the mantissa gui builder which is part of netbeans.

I've used GroupLayout as well. Again, its a standard JDK layout manager as of Java6, but you can find the library separate as well.

I've always been a big fan of the GridBagLayout. It resembles HTML tables a lot so it is intuitive to those web programmers.

I started off using various nested layouts, then moved over to GridBagLayout (which is pretty frustrating). Since then I tried FormLayout (but found it wasn't suited to anything but forms) and settled firmly on TableLayout, which overall I'm very happy with.
Since then I've discovered MiGLayout and although I haven't done much more than play with it, it seems very capable, quite similar to TableLayout and probably a little cleaner.
The big plus for me is that MiGLayout is set to become part of the JDK, so I intend to use it pretty much exclusively when it does.
The other thing to remember is that no matter which heavy-weight LayoutManager you settle on, there is always a place for some of the simpler layout managers such as GridLayout. I've seen some horrible things done with GridBagLayout that could have been done much more easily with a simpler layout manager.

I prefer to minimize dependencies on 3rd party libs, so it's usually BoxLayout for dialogs and GridBagLayout for "complicated" layouts. GridBagLayout is easy enough to understand, but a bit hard to configure. I wrote myself a tool for creating the code from HTML layouts (hope that helps others too):
http://www.onyxbits.de/content/blog/patrick/java-gui-building-gridbaglayout-manager-made-easy

The only layout manager that I have found, that I actually like is the Relative Layout Manager. The Relative Layout Manager works in a way that is consistent with how dialog boxes are conceptually organized. One draw-back is that while this layout manager deals with additive constraints. It does not seem to deal with ratio constraints. Fortunately it is pretty well designed, and I was able to implement this feature.

I use BorderLayout 90% of the time while nesting BoxLayout and SpringLayout

I'm a bit of Java newbie.
I tried GridBagLayout, gave up, then tried BoxLayout, then gave up, then made my own Custom Layout which worked. With GridBag and Box I put my best guess in and the Layout engines decided to do something different, without any apparent way to debug them.
With my custom layout, I could print out coordinates and widths and heights, to find out where it was going wrong. Its a bit mathy placing things but you've got the full power of java to use rather than the limited vocabulary of one of the builtin layout managers.
Of course it was just for a home project, you'd never be allowed to do this at work.

I use GridBagLayout for form like layouts, use BorderLayout for simple layouts, and FlowLayout for number of horizontal icons/buttons that have some spaces in between. Netbeans is also a good GUI builder that can avoid a lot of tedious layout codings to save your time.

I have started using Swing recently and I am using GridBagLayout.

I was sick of all those layoutmanagers that needed alot of setup, werent very readable or exhausting to do manually, so I wrote my own very simple laoutmanager which uses the abstraction of two photocorners keeping each component in place. You can add your component like this: parent.add(child,"topleft(0, 0.5)bottomright(0.5,1.0)");
Have a look here https://github.com/hageldave/UsefulStuff/blob/master/src/PhotoCornersLayout.java ;)
you're responisble for a correct layout yourself though, cause it's not checking overlappings or other shortcommings of your layout.

Related

Is using more JPanels and the use of the setBounds() method okay?

I have written many simple GUIs, they worked fine. However as a beginner I always think that my way of writing user interfaces is not very good practice.
Is it proper practice if one uses more panels to get the desired interface? Also is the use of the setBounds() method good?
The less sub-components you use, the more responsive your UI is going to be. Simply because it has less things to deal with.
I would not recommend using 'setBounds` as it is creates inflexible UI in most cases. I would encourage you to start using layouts such as BorderLayout, FlowLayout etc. The most versatile of them is MigLayout
Here is more general information about Swing layouts: https://docs.oracle.com/javase/tutorial/uiswing/layout/visual.html

How to retroactively make a java app fit different screens

I have a fairly large (6000 lines) java application with over 40 buttons etc. and fixed window size.
This is creating problem for people who wants to use it for some it is too small for others it is too large with no scrolling! How can I retroactively make it fit different screens?
Thanks
If yours is a Swing GUI (you have not mentioned this yet)
Don't use fixed size anything.
Use layout managers and nested JPanels to do the heavy work for you.
One comment to your question mentions using GridBagLayout, but I suggest that you avoid using this, that you instead use nested JPanels that use simpler layout managers, or use MigLayout.
To fill the Screen, set the extended state appropriately: setExtendedState(JFrame.MAXIMIZE_BOTH)

Two JPanels overlapping?

This is the code I'm dealing with: http://pastie.org/1501054 When you run this, for some reason, the two panels overlap. Why is this so? Any way I can fix it?
The ActionListener that is provided as an argument is irrelevant to this part of the program.
Also, where can I find a good swing tutorial that uses Eclipse?
I am not seeing overlapping panes when I run your code. I wonder if you can post a screenshot of the effect that you see.
As for tutorials in Eclipse. I would suggest using Windows Builder pro in Eclipse for building Java GUI. This is an excellent product (free) and very good documentation on the site.
While I'm not sure what you want the final result to look like, here's a few of my suggestions.
In the snippet where you add the warning panel to the JFrame
warningPanel.add(warningLabel);
contentPane.add(warningPanel);
pack();
contentPane being the container returned by JFrame.getContentPane()
JFrames by default use the BorderLayout, and so,
contentPane.add(<someComponent>)
is identical to
contentPane.add(<someComponent>, BorderLayout.CENTER)
You also add the mainPanel the same way, and you can't have two components with the same constraints, so instead set the warningPanel to BorderLayout.NORTH
contentPane.add(warningPanel, BorderLayout.NORTH)
And also remove the call to pack() in that code snippet, since you call it later on in your code.
Hope this helps.
PS
As for GUI building in Eclipse, this previous question on Eclipse GUI Builder plugins maybe of use. I can't speak for tutorials on using Swing in Eclipse, but a quick google search digs up this tutorial using the Eclipse Visual Editor project
When you say you want a good swing tutorial for eclipse, do you want a GUI builder or a tutorial on Swing? Swing is all about layouts. Once you get that down, it's a piece of cake. Just start with flow layouts.
If you want a GUI builder, use Netbeans. It's incredible!
As for the overlap, it's not an overlap, but an overwrite. You can only have one panel in BorderLayout.CENTER, the default location.
If you want them side by side, do getContentPane().setLayout(new FlowLayout());
Or just add(panel, BorderLayout.SOUTH)
Yes I see the warning label is over lapping the first row
That is because You didnt specify the layout for your contentpane.
Heres how you fix it
contentPane.setLayout(new GridLayout(2,1));
add this line under
Container contentPane = getContentPane();
and I think you should change your warning panel to gridlayout 1 and 1 not 0 and 1 because you still have 1 row and 1 column

Need help with Layouts in Swing

I'm using Java Swing and I have the following problem:
I have a class TnaiPanel that extends JPanel. In this class I am creating 3 components and then lay them out in a horizontal line using a BoxLayout.
Also, I have a class TnaimDinamimPanel that also extends JPanel. This class contains multiple occurances of TnaiPanel, layed out vertically using a BoxLayout.
Also, I have a class MainFrame that extends JFrame. This frame contains a menu-bar and one main panel. The main panel can change (when choosing a certain menu-item, I create a new panel and set it to show as the main panel of the frame).
Now, for some reason I get "BoxLayout can't be shared" when I add the newly created TnaimDinamimPanel to the components of the frame.
I don't mind using different layout objects.
The result I want to get is a sort of "table" of components, where each TnaiPanel will have fixed component sizes and spacing, essentially serving the role os a "row" in the "table".
Thanks,
Malki.
You probably create only a single BoxLayout instance. Create a new one each time you need one (i.e. one per TnaiPanel, one per TnaimDinamimPanel and probably one per MainFrame).
To answer the second part of your question, ie "having a table of components", I would say that you can't do it with different panels, except if you start setting the individual min, pref and max sizes of components and panels, which is highly unadvised.
If you need to have correct alignment as in a table of components, then you need to put all your components in one panel, which also means you need to use only one layout. However, the only default swing layout that can allow you to do what you want is the GridBagLayout. Actually the GroupLayout (java 6) would also fit the bill but it absolutely requires a graphical designer (eg the one within netbeans).
If, like me, you are allergic to builders, then you'd better use one 3rd-party LayoutManager that is intended to be use programmatically (I would not consider GridBagLayout to be in this category although I have already used it that way in the past).
MigLayout (as suggested by Skeptic) is one option. Another option is DesignGridLayout which might fit your purpose better and is easier to use than MigLayout.
Try MiGLayout instead.

Swing GUI components too tighly packed

In the Java Swing app I made it seems to me that all the component are too tightly packed.
In QT one can specify padding and margins for the layout.
Is there something similar for swing?
alt text http://img12.yfrog.com/img12/9612/screenshotscreenerconfi.png
Here is a screen shot of my application that I thing is too tight (is it? what do you think?.
Thanks.
Take a look to the GridBagLayoutManager. Its the most compex layout manager but everything can be acomplished whith it.
It uses the GridBagConstraintObject which has the inset property, it specifies the separation to the top, bottom, left and right components.
example: GridBagConstraintObject.insets.left=20
You could use MiGLayout as your layout manager. It allows all kinds of customizations, including margins/paddings.
You could achieve a much better layout for the example above by using DesignGridLayout in just a couple of lines of code (one per row in your layout). DesignGridLayout will automatically use the correct spacing for the runtime platform.
besides I would highly suggest that you DON'T use TitledBorders in your form because it prevents ANY LayoutManager (as advanced as it may be) from automatically aligning correctly the various components across different groups. Instead you could use a JLabel with a JSeparator (there are examples in DesignGridLayout, but this works with any other LayoutManager).
Since Java 1.6 swing there is a new GroupLayout manager that make this kind of works easier.
For instance there is a method: setAutoCreateGaps() that:
...you add two components to a SequentialGroup a gap between the two components is automatically be created...
For instance:
What LayoutManager are you using? Adding margins is quite easy, it depends however on the specific LayoutManager used.
FormLayout is another good layout manager. With a good GUI editor like JFormDesigner it makes GUI building easy enough. JFormDesigner actually automatically adds sufficient padding in most cases. I have to recommend against using GridBagLayout. It does the job alright, but is very complex which makes it difficult to use and maintain.

Categories

Resources