How to create a simple GUI in Java

Standard

A lot of time I asked myself about GUI in JAVA. I want to do this article to explain better about how to create a simple GUI in JAVA. We must have in our mind three things:

  1. JFrame
  2. JPanel
  3. Kind of Layout
    1. BorderLayout
    2. FlowLayout
    3. GridLayout
    4. (…)

What is the difference between JFrame and JPanel ?

A JFrame object is the physical window that you’ll be working with in the Swing API. Making a window appear on the screen is easy enough. Here’s the code:

JFrame frame = new JFrame("Title Bar Text");
frame.setSize(256,256);
frame.pack();
frame.setDefaultCloseOperation(frame.EXIT_ON_CLOSE);
frame.show()

JPanel is a generic lightweight container.We will put inside of  JFrame. Like this:

JFrame frame = new JFrame("Title Bar Text");
JPanel panel = new JPanel();
frame.setSize(256,256);
frame.setDefaultCloseOperation(frame.EXIT_ON_CLOSE);
frame.getContentPane().add(panel);
frame.pack();
frame.show();

Layouts

1.BorderLayout

http://download.oracle.com/javase/1.4.2/docs/api/java/awt/BorderLayout.html

A border layout lays out a container, arranging and resizing its components to fit in five regions: north, south, east, west, and center. Each region may contain no more than one component, and is identified by a corresponding constant: NORTH, SOUTH, EAST, WEST, and CENTER. When adding a component to a container with a border layout, use one of these five constants.

2.FlowLayout

http://download.oracle.com/javase/1.4.2/docs/api/java/awt/FlowLayout.html

A flow layout arranges components in a left-to-right flow, much like lines of text in a paragraph. Flow layouts are typically used to arrange buttons in a panel. It will arrange buttons left to right until no more buttons fit on the same line. Each line is centered.

3.GridLayout

http://download.oracle.com/javase/1.4.2/docs/api/java/awt/GridLayout.html

The GridLayout class is a layout manager that lays out a container’s components in a rectangular grid. The container is divided into equal-sized rectangles, and one component is placed in each rectangle.

There are others layout managers, you can look some these layouts here:

http://download.oracle.com/javase/tutorial/uiswing/layout/visual.html

There is a Java Course talking about layouts:

http://download.oracle.com/javase/tutorial/uiswing/layout/index.html

Some examples that I did:

BorderLayout Code

FlowLayout Code

GridLayout Code

 

Reference
JAVA API
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s