č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:

pátek 20. ledna 2012

Eclipse: Manual and Automatic Code Formatting

I like automatic code formatting in the Eclipse IDE. For Java see the settings in Window -> Preferences -> Java -> Code Style -> Formatter. I Just hit CTRL+SHIFT+F time from time and let the IDE do the boring job for me.

Occasionally, I want the different result then the Eclipse Formatter produce. Especially when a method has many parameters. Sometimes I like to have all of them on one line, sometimes I like to break them into multiple times. Of course, the Eclipse automatic formatter cannot be configured to meet wishes.

The Eclipse formatter has a nice option On/Off Tags:
  • @formatter:off
  • @formatter:on
But it's tedious and ugly to write these tags into the code. (Even Code templates does not simply usage of On/Off Tags very much). Much more simpler solution is to append the Java comment // ant the and of line, which you want to break. For example, I have configured the Eclipse formatter to have all method parameters on a single line. But when I write
this.someMethod(param1, //
    param2, //
    param3, //
    param4, //
    param5);
Then the CTRL+SHIFT+F reformatting let this piece of the code as is.