Create a Container example

With this tutorial we shall show you how to create a Container in a Java Desktop Application. The Container component in a very important one because it gives you the ability to organize and group together the components you want.

In short in order to create a Component in a Java Desktop Application, one should follow these steps:

  • Create a new Frame and a new Panel wich will play the role of the Container.
  • You can the use the Panel.add method to add the Components you want with the oriantation and to the position you want.

Let’s see the code:

package com.javacodegeeks.snippets.desktop;

import java.awt.BorderLayout;
import java.awt.Button;
import java.awt.Component;
import java.awt.Frame;
import java.awt.Panel;
import java.awt.TextArea;

public class CreateContainerExample {

  public static void main(String[] args) {

    // Create a frame
    Frame frame = new Frame("Example Frame");


* Create a container with a flow layout, which arranges its children 

* horizontally and center aligned.

* A container can also be created with a specific layout using

* Panel(LayoutManager) constructor, e.g.

* Panel(new FlowLayout(FlowLayout.RIGHT)) for right alignment

    Panel panel = new Panel();

    // Add several buttons to the container
    panel.add(new Button("Button_A"));
    panel.add(new Button("Button_B"));
    panel.add(new Button("Button_C"));

    // Add a text area in the center of the frame
    Component textArea = new TextArea("This is a sample text...");
    frame.add(textArea, BorderLayout.CENTER);

    // Add the container to the bottom of the frame
    frame.add(panel, BorderLayout.SOUTH);

    // Display the frame
    int frameWidth = 300;
    int frameHeight = 300;
    frame.setSize(frameWidth, frameHeight);




This was an example on how to create a Container.

Byron Kiourtzoglou

Byron is a master software engineer working in the IT and Telecom domains. He is an applications developer in a wide variety of applications/services. He is currently acting as the team leader and technical architect for a proprietary service creation and integration platform for both the IT and Telecom industries in addition to a in-house big data real-time analytics solution. He is always fascinated by SOA, middleware services and mobile development. Byron is co-founder and Executive Editor at Java Code Geeks.
Notify of

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Inline Feedbacks
View all comments
Back to top button