When Frame.pack method Can Be Used While Designing Swing Desktop Based Application?

Spread the love

This article is based on my experience and a leaning on swing application. I was designing a desktop based swing application with some JTextfields,JButtons some picture which were hidden in nature. Based on some selection or some data they needed to activate.I was using the below code

frame.setSize(1200, 300);

But when user tried to enter some data and based on the action like focus out some image got displayed.

public void focusLost(FocusEvent e) {
// TODO Auto-generated method stub

This time, to my surprise frame could not resized and could not show my image.I had to drag the frame [manually resize].
But if was printing frame’s height and width by..


It was actually printing 1200 and 300 which I set before. But effectively It was showing something 200*400 frame.I started analyzing and tried o find out the root cause of the problem. Then I found the the actual cause …It was the frame.pack() method which was causing the problem.When I commented the step It worked. But open a very big ugly frame of 1200*300.
Ok…the next question could be when should we use frame.pack()???

The probable answer was when your frame is fixed in size and you were not expecting new element will be visible in the same frame,pack() was the right method to call.

it calculated the actual width and height based on the frame’s all visible properties..say I had a visible JTextField of size (height=5 and width=20) and a button of size (height=5 and width=40).If they were in default flowlayout then frame tried to enter both of them in the same line whose height will be 5 and width60.
[even if I had asked to resize the frame to 1000*300 it opened height of 5pix and 60 pics.]Pack method to make the smallest space in a frame so that They can be useful

Below are the great tutorials:

READ  Class SecurityManager in Java

Spread the love

Leave a Comment

Your email address will not be published. Required fields are marked *