Why should we write setVisible() at last?

In many posts, I have been mentioning to push down the setVisible() to last, Did I? But why? I think, I have not mentioned a reason before. Now, I decided to write this post with enthusiasm. The reason is I'm going to make it a bit funny with an analogy.

You know that setVisible() is used to make a component visible. Mostly we will be using it to show JFrame. Fine, until recently I have been writing setVisible() at the top before adding all the components. Then, I recently started turning the game around.

Why push add() to the top? (The analogy, the fun!)

You can make a JFrame visible before adding the components. Right? But how will it look? Consider a general life situation, say you want to go out for a party.. You get ready before you attend the party, you bath, dress up, makeup. But how will it look when you do after attending/in the party? Just imagine!! Lol!

You'll need to do the complete make up before you make the frame ready to get displayed. Fine.

Also, writing setLocationRelativeTo() before sizing the frame will not give the desired effect because it depends upon the size of the frame. So the frame needs to have a size before it's location is set relative to something. If its size is changed after the location is set, then you got an undesired output. So, be careful. See the following program, you get an undesired output if you execute it.


import javax.swing.*;
class LocationFail
{
    public static void main(String args[])
    {
        JFrame f=new JFrame("My Frame");
        f.setVisible(true);
       
        f.setLocationRelativeTo(null);
       
        // the wrong thing!!
        // doesn't appear at the center
        f.setSize(400,400);
    }
}

Even when you are working with pack() you need to add all the components first, pack the frame and then invoke setLocationRelativeTo() and then setVisible(), now this looks great!

Are there any analogies or counter arguments that you would love to fire on me? Discuss them in comments below.

The greatest compliment you can give me is when you share this with others. I sincerely appreciate it :)

“If you can imagine it, you can achieve it; if you can dream it, you can become it.” - William Arthur Ward


Posted by at on

Tags: Swing Components, Tips,