Take the 2-minute tour ×
Programmers Stack Exchange is a question and answer site for professional programmers interested in conceptual questions about software development. It's 100% free, no registration required.

I have been trying for years to master Swing layout managers with no success. Every time I need to do something with Swing, it is like pulling nails to get the visual components to line up the way I want them to. I am familiar with frameworks like Matisse but that's not the point.

My question is: Why does Swing even need layout managers? It seems like an overcomlicated paradigm. What I would like to be able to do is jave a simple JFrame and then for each component (like JLabel) simply specify X and Y coordinates where I want it to be situated -- done deal. Can anybody explain what is wrong with this simple approach that would work predictably 100% of times? Or is there an actual layout manager that does things exactly like this?

share|improve this question
    
a) You can specify coordinates for your components in Swing. b) Unless your windows are a fixed size, this is a terrible idea because the components will never move or scale with the window. –  Glenn Nelson Jan 18 '13 at 18:48
1  
in that case the X,Y can be percentages on the X and Y coords so the position changes with the window size. E.g. if you wanted it to be in the middle, you'd set 50,50 etc. –  amphibient Jan 18 '13 at 18:52
    
So what, top-left corner would be 50%, 50%? Wouldn't that look odd? How would you do sizes, then? With percents as well? Absolute positioning, which you can do, is terrible mostly because you have to consider how the thing will look at feel at every possible permutation of window size/screen resolution. It may end up looking great on your 1024x768, but wonky and stretched on my 1900x1280. –  Roddy of the Frozen Peas Jan 18 '13 at 19:13
1  
Try TableLayout. In my opinion it's much easier to use yet as powerful as for example GridBagLayout. –  msell Jan 18 '13 at 19:17
    
@msell, that may be a solution for my frustrations. is that part of Google API? –  amphibient Jan 18 '13 at 19:33
show 5 more comments

6 Answers

up vote 5 down vote accepted

What I would like to be able to do is jave a simple JFrame and then for each component (like JLabel) simply specify X and Y coordinates where I want it to be situated -- done deal.

You can do that with null layout:

jPanel.setLayout(null);
jLabel.setBounds(5, 5, 200, 300);
jPanel.add(jLabel);
jFrame.add(jPanel);
share|improve this answer
add comment

Maybe you're too young to remember when programming without layout managers was more common. Either you had to fix your screen at one size, which worked great unless you actually needed to share your application with someone who used a different screen resolution, or you had to deal with scaling that looked really bad.

Part of the problem is what you might consider "natural" and "obvious" scaling is actually quite complex under the hood. Some components, like a text area, can naturally be resized in both directions and still look pretty good. Some components, like a combo box, only look okay when scaled in the horizontal direction, and some components, like buttons, rarely look natural when scaled more than a little bit in either direction. Layout managers let you mix and match components and still make the scaling look natural.

share|improve this answer
add comment

Other toolkits have equivalent concepts (e.g., Tk has geometry managers) as well, and they are absolutely central to having a GUI that is not fixed at one exact size. That matters when:

  1. you have fonts that can change in size for accessibility reasons, or
  2. you have different sizes of screens, or
  3. you have resizable windows, or
  4. you have variable amounts of content in some components.

That's not a complete list of reasons why you might want adaptive sizing, but it does illustrate that you may well not have control over the precise placement and sizing of things even if you might want it. Far better to stop trying to control things at the pixel level and to instead leave the computer to look after that for you following more general rules that you describe; what layout managers do is enforce those rules.

FWIW, writing a good layout manager is hard. Really hard. In fact, the one I know of that gives the best layouts in my experience (Tk's grid manager, which is a sort of souped-up GridBagManager except without the suck) is internally a complicated simultaneous equation solver with some scary heuristics to ensure that an answer pops out even when the user's directives don't give a solution. It's also had a few man-years of effort poured into its development (really!) so I wouldn't expect it to be reproduced easily. Because of the general difficulty in doing layout managers well, most people who write them tend to write very specific ones that don't actually do a particularly smart job but where the implementation is simple enough that it is at least easy to handle the simple cases they actually care about.

share|improve this answer
    
I remember how many Windows apps would break if you turned on the large fonts for accessibility; luckily, they'd usually only become hard to use rather than crashing, but it wasn't a certain thing that… –  Donal Fellows Jan 18 '13 at 23:12
    
In all the layout managers I have used I think Xcode (since they merged Interface Builder with it) is pretty hard to beat. I don't program for Mac OS X / iOS any more but I do miss the tools. –  Cromulent Jan 19 '13 at 13:29
1  
@Cromulent: I think you totally misunderstand. That's a graphical tool for designing GUIs (and an IDE) but a layout manager is a (small) software module for enforcing programmatic rules about how to arrange components within the space provided by a containing component. The most trivial one is to just use a fixed coordinate; that's easy, and wrong because it doesn't respond to size changes. A GUI design tool can be used to write a configuration for a layout manager instance; I've seen that done, but don't know if that's exactly how you do it with Xcode (as front end). –  Donal Fellows Jan 21 '13 at 0:38
    
Ah right. Thank you for the correction. –  Cromulent Jan 21 '13 at 6:50
add comment

Well, Swing need layout manager because its supposed to be cross platform, and thus will render components of different size on different platform. By using math rule to line elements it make it much more portable.

By the way, if you want good control over the placement while still remaining fluid, you can check GroupLayout. Its not perfect, but it give you a relatively fine control, and I use it very often

share|improve this answer
add comment

Consider using MigLayout. It's a comprehensive layout manager that I haven't had any issues with. To get an initial taste of what it's capable of and how easy it is to use, look at the sample application linked to from the home page. Make sure you try resizing the window to see how the user interface is able to adapt to the size of the screen.

The core reason behind the layout managers is to allow your application to scale elegantly to what your user wants or needs. MigLayout makes this easy by providing a huge number of easily tweakable constraints and rules, some of which make it more powerful than HTML+CSS in some areas (though that's finally changing). It also includes a debug mode which shows you exactly what it's trying to do, and has the ability to arrange buttons according to a user's operating system.

A few examples of absolute positioning:

// adds item at 100, 100
panel.add(item, "pos 100, 100");
// adds item 10% + 5 "logical pixels" + 1 inch from left side of parent
// and centers itself 75% of the way down parent component
panel.add(item, "pos (10% + 5lp + 1in) .75al"); 

Details can be found on the tutorial, sample application, and cheat sheet linked to from the main page.

share|improve this answer
add comment

As already mentioned layoutManagers because screens come in a lot of different sizes.

As already mentioned I would suggest using TableLayout

Most of my screens are fairly simple, I have my own front-end to Swing that allows me to define simple screens like:

pnl.addLine("Record Name", sfRecordName);
pnl.addLine("Description", sfDescription)
       .setHeight(DESCRIPTION_HEIGHT);
pnl.addLine("Record Type", sfRecordType);
pnl.addLine("System",      sfSystem)
       .setGap(BasePanel.GAP0);
pnl.addLine("List",        sfList);

Behind the scene the addLine method uses tableLayout to layout the screen, it also will

  • optionally set the name of the field (to the prompt) which is useful in some Swing Testing tools (e.g. early versions of Marathon)
  • Do language conversion

Have a look around, there are various Swing front-end available

share|improve this answer
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.