Search code examples
javaswingjframejlabeljtextfield

Why is the window too small if I don't resize it?


I am wondering why when I enter this code without resizing the window, I cannot see anything:

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

public class GolfScoresGUI 
{
    public static void main(String[] args)
    {
        JFrame frame = new JFrame("GolfScoresGUI");
        JLabel label = new JLabel("Did you score it? ");
        JTextField textField = new JTextField(10);
        frame.setVisible(true);
        frame.getContentPane().add(textField);
    }
}

Solution

  • add your components to a panel on which you call setPreferredSize, add the panel to the frame and call JFrame.pack().

    JFrame.pack() updates the size of the frame to take the minimum possible size, given the size on its contained elements.

    If you don't call it, the size will be something like 0x0, explaining why you don't see anything.

    JFrame frame = new JFrame("GolfScoresGUI");
    JPanel panel=new JPanel();
    panel.setPreferredSize(new Dimension(600,400)); // Not mandatory. Without this, the frame will take the size of the JLabel + JTextField
    frame.add(panel);
    
    JLabel label = new JLabel("Did you score it? ");
    JTextField textField = new JTextField(10);
    panel.add(label);
    panel.add(textField);
    
    frame.setVisible(true);
    frame.pack();
    

    EDIT

    btw, you should also add this line so that your application stops when you close the frame :

    frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);