Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Adding Contents to JFrame Before Setting Visible

I have a JFrame that I create in the main function. I want to add a JTextField to it. The problem I'm having is that the JFrame is created and then - with about a second delay - the JTextField is added. Is there a way I can draw the text field to my window and then show all at once? Thanks in advance!

For reference, here is my code:

public class Window {

public static final JFrame window = new JFrame();
public static final JTextField input = new JTextField();

private static void loadWindow(){

    window.setSize(800, 600);
    window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    window.setLayout(new FlowLayout());
    input.setPreferredSize(new Dimension(400, 60));

    window.add(input);
    window.setVisible(true);

}

public static void main(String[] args){

    loadWindow();

}

}

Here's the timeline of what's happening:

First second:

enter image description here

Second after:

enter image description here

like image 574
Ood Avatar asked May 24 '26 05:05

Ood


1 Answers

Chalk this one to weirdness...

I changed

public static final JTextField input = new JTextField();

to

public static final JTextField input = new JTextField(20);

And it worked fine...

I would however encourage you...

  • to avoid using setPreferredSize as it won't always work on every platform as you don't control the rendering pipelines which can affect the amount of space a component will need in order to render properly
  • Start your UI's in the EDT...

For example...

EventQueue.invokeLater(new Runnable() {
    @Override
    public void run() {
        try {
            UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
        } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
            ex.printStackTrace();
        }

        loadWindow();
    }
});
like image 71
MadProgrammer Avatar answered May 25 '26 20:05

MadProgrammer