Saturday, July 24, 2010

Java Tips: How to use Grid Layout in Java Swing.

They are many types of layouts in Java. But arranging in a tabular order needs us to use Grid Layout. Grid layout in Java Swing is something in a frame that arranges the components in the form of rows and columns. The size of the components, especially buttons, text boxes change as we resize the actual JFrame window. So, when the window is maximised, the components will be distributed accordingly resulting in unusual look and feel. For example, just imagine you have added 4 buttons to a frame by Grid Layout. You would see everything on the frame filled with buttons. This is very awkward to view and has to be avoided.

Thus, it is necessary to fix the components' sizes according to the application or the program. That is, grid layout is good looking as far as the components are of sufficient size not large and not small. In addition to the way the components size is, the resizing of the frame would make it look very awkward which results in the end-user dissatisfaction and an ugly user interface.

Fortunately, there is a solution to this problem. There are two things which you have to remember while using the Grid Layout in Swing.
  1. Set the borders of the frame so, that the components are of good size. This can be done by this piece of code:
    setBorder(BorderFactory.createEmptyBorder(top_margin, left_margin, bottom_margin, right_margin));
  2. After setting the borders, you have to decide the size that the JFrame should be. You can set size by using setSize(width,height).
  3. The most important thing in this discussion is to avoid it from being resized. You can avoid resizing of frame window by the following function: setResizable(false);
Now , you can enjoy all the privileges that Grid Layout provides without being much concerned about the look and feel.

No comments:

Post a Comment

Related Posts Plugin for WordPress, Blogger...