I have a simple Swing GUI. (and not only this, all swing GUI I have written). When run it, it doesn’t show anything except blank screen, until I resize the main frame, so every components have painted again, and I can show them.
Here is my simple code :
public static void main(String[] args) {
JFrame frame = new JFrame("JScroll Pane Test");
frame.setVisible(true);
frame.setSize(new Dimension(800, 600));
JTextArea txtNotes = new JTextArea();
txtNotes.setText("Hello World");
JScrollPane scrollPane = new JScrollPane(txtNotes);
frame.add(scrollPane);
}
So, my question is : how can when I start this class, the frame will appear all components I have added, not until I resize frame.
Thanks 🙂
Do not add components to
JFrameafter theJFrameis visible (setVisible(true))Not really good practice to call
setSize()on frame rather callpack()(CausesJFrameto be sized to fit the preferred size and layouts of its subcomponents) and letLayoutManagerhandle the size.Use EDT (Event-Dispatch-Thread)
call
JFrame#setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE)as said by @Gilbert Le Blanc (+1 to him) or else your EDT/Initial thread will remain active even afterJFramehas been closedLike so: