čtvrtek 13. září 2012

Java Swing: MigLayout, JScrollPane and JTextField Showing Horizontal Scrollbar

MigLayout is a great layout manager for Java Swing. However, it needs some time to discover it's nooks and crannies. One common problem is with components inside JScrollPane.

We place all components inside the JPanel, which has a JScrollPane as parent. And we use MigLayout mostly with fill and grow parameters. Such layout ensures that a user can access all components by scrolling when she has a small screen.

But I have a faces a problem with JTextField containing a very long text. I usually use MigLayuot

growx, width 50::

constraints for text fields. However, when a text files contains a very long String, then it forces JScrollPane to to enlarge it's width and show the horizontal scrollbar. The user usually need the text field to be as long as possible, but not to overflow the screen width, if possible. After a while, I have found a proper and simple solution, just set the preferred size as minimum:

growx, width 50:50:

Note: I have described the problem using component constraints, the solution is similar with row constraints

fill, grow, 50:50: