Java Swing : why must resize frame, so that can show components have added

后端 未结 2 893
傲寒
傲寒 2020-11-28 15:53

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 e

2条回答
  •  自闭症患者
    2020-11-28 15:55

    Your simple code is missing a few things.

    You have to invoke SwingUtilities to put the Swing components on the event dispatch thread.

    You should call the setDefaultCloseOperation on the JFrame.

    You have to call the JFrame methods in the correct order. The setSize or pack method is called, then the setVisible method is called 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());
        }
    
    }
    

提交回复
热议问题