awt
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 newPanel
wich will play the role of theContainer
. - 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); frame.setVisible(true); } }
This was an example on how to create a Container.