1. Home
  2. Computing & Technology
  3. Java

Create a Simple Window Using JFrame

By , About.com Guide

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);
Explore Java
About.com Special Features

Holiday Central

What to eat, where to go, fun things to do and how to save money on the perfect gifts. More >

Family Tech Center

Stay connected and entertained with reviews on tips on the latest HDTVs, cellphones and more. More >

  1. Home
  2. Computing & Technology
  3. Java
  4. Tutorials
  5. Add a JLabel to the JFrame

©2009 About.com, a part of The New York Times Company.

All rights reserved.