To make the window worth seeing, we should put a graphical component inside it. Add the following lines of code to the createWindow function to create a new JLabel object
JLabel textLabel = new JLabel("I'm a label in the window",SwingConstants.CENTER); textLabel.setPreferredSize(new Dimension(300, 100));
A JLabel is a graphical component that can contain an image or text. To keep it simple, it’s filled with the text “I’m a label in the window.”, and its size has been set to a width of 300 pixels and height of 100 pixels.
Now that we have created the JLabel, it needs to be added to the JFrame:
The last lines of code for this function are concerned with how the window is displayed. Add the following:
//Display the window. frame.setLocationRelativeTo(null);
The above line makes sure that the window will appear in the center of the screen. Next,
The pack() method is a handy way to size the window. It looks at what the JFrame contains, and automatically sets the size of the window. In this case, it ensures the window is big enough to show the JLabel.
Finally, we need show the window: