If you take a look at the docs for Window.setVisible()
, you might notice a note about the input parameter that says
The Window will be validated prior to being made visible.
Validation is the key to making new components show up when you add them to a window. You have two options:
Move the call to setVisible
to the end of your code, once everything is added to the window:
JFrame frame = new JFrame();
frame.setLayout(new BorderLayout());
frame.setSize(500,300);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel panel = new JPanel();
frame.add(panel, BorderLayout.CENTER);
frame.setVisible(true);
Re-validate the frame yourself after adding the panel:
JFrame frame = new JFrame();
frame.setLayout(new BorderLayout());
frame.setSize(500,300);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
JPanel panel = new JPanel();
frame.add(panel, BorderLayout.CENTER);
frame.validate();
A note from the docs for Container.validate()
:
Validating the container may be a quite time-consuming operation. For performance reasons a developer may postpone the validation of the hierarchy till a set of layout-related operations completes, e.g. after adding all the children to the container.
Using the first option is probably better.
Clarification
Keep in mind that the background color of a JPanel
is the same as the background color of the JFrame
's content pane by default. You will not be able to determine that it was added correctly visually. At @W.K.S.'s suggestion, you can change the panel's color so you can see it clearly in the frame:
JFrame frame = new JFrame();
frame.setLayout(new BorderLayout());
frame.setSize(500,300);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel panel = new JPanel();
panel.setBackground(Color.RED);
frame.add(panel, BorderLayout.CENTER);
frame.setVisible(true);
Don't forget to import java.awt.Color;
in this case.