I've encountered what I am pretty sure is a glitch, and have not found any way around it. I, at present, have only a simple window that has a text field and a label. When I first run the program, what appears is an empty window, when I resize the window, either by maximizing or just manually resizing a little bit, the components appear, what's going on here?
public class Calculator {
public static void main(String[] args) {
JFrame mainFrame = new JFrame("Calculator");
mainFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
mainFrame.setSize(300,400);
mainFrame.setLocationRelativeTo(null);
mainFrame.setVisible(true);
JPanel mainPanel = new JPanel();
mainFrame.add(mainPanel);
JTextField mainField = new JTextField(20);
mainPanel.add(mainField);
JLabel mainLabel = new JLabel("Orange");
mainPanel.add(mainLabel);
}
}
By default the size of all components is (0, 0), so there is nothing to paint.
Components need to be added to the frame BEFORE the setVisible() method. Then when the frame is made visible the layout manager is invoked and components are given a size/location.