Frustration with Java Swing layout managers

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?

11

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);

5

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.

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.

3

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.

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

I believe the reason this appears so complex is that the behaviour you refer to is implemented by the GridBagLayout manager in standard Java. While GridBagLayout is very expressive, it also includes a large number of parameters in addition to the x,y coords that you might not care about (for example, components spanning multiple cells, anchoring/filling in different ways etc).

While these options can make the documentation a little daunting, you are free to ignore these extra parameters until you need them. Here’s a typical usage pattern for me that doesn’t sound too different to what you asked for:

setLayout(new GridBagLayout());

// Implicit location = 0,0
// We need to set the weight to be non-zero otherwise everything 
// will clump together in the middle of the frame. Apart from that, 
// we can just provide x,y coords
GridBagConstraints gbc = new GridBagConstraints();
gbc.weightx=1;
gbc.weighty=1;

add(myButton, gbc);

// Now add something at 1,0
gbc.gridx = 1;
add(myLabel, gbc);

// Now add something at 2,0
gbc.gridx = 2;
add(myOtherLabel, gbc);

// Now add something at 1,0, it should span the full width and
// it should be anchored to the bottom of the frame
gbc.gridx = 0;
gbc.gridy = 1;
gbc.gridwidth = 3;
gbc.fill = GridBagConstraints.HORIZONTAL;
gbc.anchor = GridBagConstraints.SOUTH;

add(myOtherComponent, gbc);

As you can see from the item at 0,1, you can have many constraints but you don’t need to, just specify the ones you care about.

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

simply specify X and Y coordinates where I want it to be situated

YES, when you resize the window the JLabel and text editor size will not be adjusted based on the screen.it will remain set as same positioning.

You can re adjust the layout with custom layout but its harder to use custom one compared to the layout manager.

If you choose the right layout manager , it will simplify your work lot.

But when you add the layout then the labels size will be adjusted based on the layout .

Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa Dịch vụ tổ chức sự kiện 5 sao Thông tin về chúng tôi Dịch vụ sinh nhật bé trai Dịch vụ sinh nhật bé gái Sự kiện trọn gói Các tiết mục giải trí Dịch vụ bổ trợ Tiệc cưới sang trọng Dịch vụ khai trương Tư vấn tổ chức sự kiện Hình ảnh sự kiện Cập nhật tin tức Liên hệ ngay Thuê chú hề chuyên nghiệp Tiệc tất niên cho công ty Trang trí tiệc cuối năm Tiệc tất niên độc đáo Sinh nhật bé Hải Đăng Sinh nhật đáng yêu bé Khánh Vân Sinh nhật sang trọng Bích Ngân Tiệc sinh nhật bé Thanh Trang Dịch vụ ông già Noel Xiếc thú vui nhộn Biểu diễn xiếc quay đĩa Dịch vụ tổ chức tiệc uy tín Khám phá dịch vụ của chúng tôi Tiệc sinh nhật cho bé trai Trang trí tiệc cho bé gái Gói sự kiện chuyên nghiệp Chương trình giải trí hấp dẫn Dịch vụ hỗ trợ sự kiện Trang trí tiệc cưới đẹp Khởi đầu thành công với khai trương Chuyên gia tư vấn sự kiện Xem ảnh các sự kiện đẹp Tin mới về sự kiện Kết nối với đội ngũ chuyên gia Chú hề vui nhộn cho tiệc sinh nhật Ý tưởng tiệc cuối năm Tất niên độc đáo Trang trí tiệc hiện đại Tổ chức sinh nhật cho Hải Đăng Sinh nhật độc quyền Khánh Vân Phong cách tiệc Bích Ngân Trang trí tiệc bé Thanh Trang Thuê dịch vụ ông già Noel chuyên nghiệp Xem xiếc khỉ đặc sắc Xiếc quay đĩa thú vị
Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa
Thiết kế website Thiết kế website Thiết kế website Cách kháng tài khoản quảng cáo Mua bán Fanpage Facebook Dịch vụ SEO Tổ chức sinh nhật