1. Technology

Create a Simple Window Using JFrame

By

4 of 7

Add a JLabel to the JFrame
Add a JLabel

Microsoft product screen shot(s) reprinted with permission from Microsoft Corporation.

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:

 frame.getContentPane().add(textLabel, BorderLayout.CENTER); 

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,

 frame.pack(); 

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:

 frame.setVisible(true); 
  1. About.com
  2. Technology
  3. Java
  4. Create User Interfaces
  5. Create a Simple Window - Add a JLabel to the JFrame

©2014 About.com. All rights reserved.