1

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);

    }

}
Psear
  • 105
  • 8

2 Answers2

4

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.

camickr
  • 321,443
  • 19
  • 166
  • 288
  • Ah right, but then how come the components appear whenever I resize the window? – Psear Dec 02 '17 at 16:13
  • @Psear, `how come the components appear whenever I resize the window?` Because when you resize the frame the layout manager is invoked. – camickr Dec 02 '17 at 16:14
  • Something similar had occurred to me before, so does that mean if I later have to add more components I have to set the visibility again? I tried using repaint() and that didn't work. – Psear Dec 02 '17 at 16:16
  • 1
    @Psear, You need to invoke the layout manager when you add/remove components on a visible window. This is done by invoking `revalidate()` on the panel you add/remove the components from. Sometimes you also need to invoke repaint() after the revalidate(). – camickr Dec 02 '17 at 16:17
  • Thank you, I normally do but for some reason I tried and it told me I could accept answers after 10 minutes. Not sure why. – Psear Dec 02 '17 at 16:57
0

You're adding components to the frame after calling setVisible(true). This question has already been asked.

Java items appear only after the window is resize

James F
  • 130
  • 1
  • 10