Java Swing: why resize the frame to add components added

I have a simple Swing GUI. (and not only that, the whole swing GUI that I wrote). When it starts, it shows nothing but a blank screen until I change the size of the main frame, so all the components are drawn 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 all the components that I added appear in the frame until I change the size of the frame.

Thanks:)

+4
source share
2 answers
  • Do not add components to the JFrame after the visibility of the JFrame ( setVisible(true) )

  • It is not a good practice to call setSize() on the frame rather to call pack() (Causes the JFrame to fit the size and layout of its subcomponents) and the LayoutManager handles the size.

  • Use EDT (Event-Dispatch-Thread)

  • call JFrame#setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE) as @Gilbert Le Blanc said (+1 to him), otherwise your EDT / Initial stream will remain active even after closing the JFrame

Same:

 public static void main(String[] args) { //Create GUI on EDT Thread SwingUtilities.invokeLater(new Runnable() { @Override public void run() { JFrame frame = new JFrame("JScroll Pane Test"); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); JTextArea txtNotes = new JTextArea(); txtNotes.setText("Hello World"); JScrollPane scrollPane = new JScrollPane(txtNotes); frame.add(scrollPane);//add components frame.pack(); frame.setVisible(true);//show (after adding components) } }); } 
+13
source

There are a few things missing in your simple code.

You must call SwingUtilities to place the Swing components in the event dispatch stream.

You should call setDefaultCloseOperation on a JFrame .

You must call the JFrame methods in the correct order. The setSize or pack method is setVisible , then the setVisible method is called the last.

 public class SimpleFrame implements Runnable { @Override public void run() { JFrame frame = new JFrame("JScroll Pane Test"); JTextArea txtNotes = new JTextArea(); txtNotes.setText("Hello World"); JScrollPane scrollPane = new JScrollPane(txtNotes); frame.add(scrollPane); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.setSize(new Dimension(800, 600)); frame.setVisible(true); } public static void main(String[] args) { SwingUtilities.invokeLater(new SimpleFrame()); } } 
+5
source

Source: https://habr.com/ru/post/1437645/


All Articles