Creating basic GUI's in Java with JFrame

Ranked #838 in Education, #20,351 overall

Lets make programming more interesting by adding GUI components

This lense will be about the creation of GUI's in Java with the use of the Swing package. This is only an introduction to the vast classes available to you as a developer to create GUI's

The boring world of the console. Is there an alternative?

Show me the GUI.

With the start of the computer generation and lack of powerful computers most program were developed using the console. Many reasons can be given. Although the programs were powerful it did not provide a user experience.

Here is an example to make use of the console. The well known "Hello World" application.


class MyProg{

public static void main(String args[]){

System.out.println("Hello World");
}
}

Enter the swing package of Java

Example to create a GUI with JFrame

To create GUI in Java we will make use of the swing package called javax.swing. This package contains a lot of classes that will create GUI components for us.

Our first objective will be create a frame. Once we have the frame we can add other components on to it.

To be able to create a frame we have to import the package called javx.swing.

import javax.swing.*

The * means import all the classes in the package.

Next objective is to look at what we want to achieve. Looking at the figure or looking at any window you will notice similarities. There is a title, its has a specific size, you can see it thus its visible and you can close, maximize or minimize the window or frame. Knowing this we need to check if there are any methods in the JFrame class that can do that for us.

The four methods that can do what we require are:
setTitle(String) - Gives the frame a title
setSize(int,int) - Gives the frame a size
setVisible(boolean) - Makes the frame visible
setDefaultCloseOperation() -Sets the operation that will happen by default when the user initiates a "close" on this dialog

Remember before we can use the methods we need to create an object of the class, the object will then have access to all the methods of that class.

JFrame j=new JFrame()

Please note that I use the default constructor to create the object of the JFrame class. Have a look in the API for the other constructors with parameters.

Once we creates an object that object will then make calls to the different methods to create the GUI for us.

Example:
import javax.swing.*;

public class MyGUI {

public static void main(String[] args) {
new MyGUI();
}

public MyGUI(){
JFrame jf=new JFrame();

jf.setTitle("My frame");
jf.setSize(300,200);
jf.setDefaultCloseOperation(jf.EXIT_ON_CLOSE);
jf.setVisible(true);
}
}

We have a frame now. Our next step will be to add components to the frame.

Adding components to the JFrame..but first we need to configure the container

We have the frame, no what?

We have created a frame. Before we create the components we need t oget access to the inside area of the frame also known as the container.

The container is the area that we will put the components like buttons onto.

To get access to this container new will make use of the method getContentPane() from the JFrame class.It returns a container for us. We need to create an object of this container since we want to make of the methods of the Container class.

Example of the syntax

Container pane=frame.getContentPane()

Please note that getContentPane returns an object of data type Container. You will notice that we dont use the new reserved keyword of Java above and yet we create an object called pane. Checek the API to confirm that getContentPane returns a Container object.

The Container class does not belong to the javax.swing package. It belongs to the java.awt package. That means to be able to make use of the Container class we will need to import the java.awt package into our class.

import java.awt.*

Now we have access to the Container class.

Next step will be to configure the layout of the container area. We will make use of the setLayout() method. And we will make the layout a grid. We do this by specifying the layout manager in this case we will make use of a grid. The gridlayout will devide the container in rows and columns. The first parameter is the number of rows and the second parameter is the number of columns.

pane.setLayout(new GridLayout(3,2))

Components are added from left to right and top to bottom when we makeuse of gridlayout.

We have configured the container to look like in the figure.

Example:
import javax.swing.*;
import java.awt.*;

public class MyGUI {

public static void main(String[] args) {

// TODO, add your application code
new MyGUI();
}

public MyGUI(){
JFrame jf=new JFrame();
jf.setTitle("My frame");
jf.setSize(300,200);

Container pane=jf.getContentPane();
pane.setLayout(new GridLayout(3,2) );

jf.setDefaultCloseOperation(jf.EXIT_ON_CLOSE);
jf.setVisible(true);

}
}

Let the games begin..We will add a label

Lets make the frame more intersting by adding a label

Now that we have created a frame and we have access to the container; we can now create components to place on our frame.

the first component that we will make use of is JLabel.

JLabel forms part of the javax.swing package. We need to make sure that the package has been imported.

To create a label we will make use of the JLabel class. We will create an object of JLabel and send a string parameter with the constructor.

JLabel l=new JLabel("I am a label")

We also will need to make sure that the components are declared globally. That means that all the methods will be able to access the member/variable. The scope of the global members are accessible to all methods.

JLabel label

Once we have created a component we can place it on the container. We will make use of the add() method

Example of adding component to container

pane.add(label)

This will add the JLabel component called label to the Container called pane.

Note in the example below how the components are added from left to right and top to bottom when using the gridlayout.

Example

import javax.swing.*;
import java.awt.*;

public class MyGUI {

JLabel l1,l2,l3,l4,l5,l6;

public static void main(String[] args) {

// TODO, add your application code
new MyGUI();
}

public MyGUI(){
JFrame jf=new JFrame();
jf.setTitle("My frame");
jf.setSize(500,300);

JLabel l1=new JLabel("label 1");
JLabel l2=new JLabel("label 2");
JLabel l3=new JLabel("label 3");
JLabel l4=new JLabel("label 4");
JLabel l5=new JLabel("label 5");
JLabel l6=new JLabel("label 6");

Container pane=jf.getContentPane();
pane.setLayout(new GridLayout(3,2) );
pane.add(l1);
pane.add(l3);
pane.add(l5);
pane.add(l2);
pane.add(l4);
pane.add(l6);

jf.setDefaultCloseOperation(jf.EXIT_ON_CLOSE);
jf.setVisible(true);

}
}

Give me some input..enter the JTextFiled

Give the user a component to enter some data

We have added some labels. The user needs to be able to enter some data. We will use the component called JTextField. To able to use the class JTextField we need to make sure that the package that includes the class is imported.

To create a object of the JTextField class we will use the following syntax/statement, the constructor is send a int value of 10 to specify the size of the textfield.

JTextField tf=new JTextField(10)

We will can add text to a textfield by maing use of the setText() method. We need to specify the JTextField object and then the setText() method

Example on adding text to JTextField object

tf1.setText("i am a text field");

If we want to make sure that the user can not edit the value inside of the JTextField we make use of the setEditable() method

Example on make JTextField not editable

tf2.setEditable(false);

Example
import javax.swing.*;
import java.awt.*;

public class MyGUI {

JTextField tf1,tf2,tf3,tf4,tf5,tf6;

public static void main(String[] args) {

// TODO, add your application code
new MyGUI();
}

public MyGUI(){
JFrame jf=new JFrame();
jf.setTitle("My frame");
jf.setSize(500,300);

JTextField tf1=new JTextField(10);
JTextField tf2=new JTextField(5);
JTextField tf3=new JTextField(7);
JTextField tf4=new JTextField(10);
JTextField tf5=new JTextField(10);
JTextField tf6=new JTextField(10);

tf1.setText("i am a text field");

tf2.setText("i am a text field and can not be changed");
tf2.setEditable(false);

Container pane=jf.getContentPane();
pane.setLayout(new GridLayout(3,2) );
pane.add(tf1);
pane.add(tf2);
pane.add(tf3);
pane.add(tf4);
pane.add(tf5);
pane.add(tf6);

jf.setDefaultCloseOperation(jf.EXIT_ON_CLOSE);
jf.setVisible(true);

}
}

Give the user some action with the button..push the button

The user will need to be able to initiate an action..that were the button comes in.

To give the user the capability to start an action, we will give the user a button. For this component we will use the JButton class. To be able to make use of this class we need to import the javax.swing package.

To create the component as a button we will send a text as an parameter that will appear on the button.

Example to create a JButton

JButton b1=new JButton("I am a button");

Once the component is created we can add it to the container with the add() method.

Example:

import javax.swing.*;
import java.awt.*;

public class MyGUI {

JButton b1,b2,b3,b4,b5,b6;

public static void main(String[] args) {

// TODO, add your application code
new MyGUI();
}

public MyGUI(){
JFrame jf=new JFrame();
jf.setTitle("My frame");
jf.setSize(500,300);

JButton b1=new JButton("Button 1");
JButton b2=new JButton("Button 2");
JButton b3=new JButton("Button 3");
JButton b4=new JButton("Button 4");
JButton b5=new JButton("Button 5");
JButton b6=new JButton("Button 6");

Container pane=jf.getContentPane();
pane.setLayout(new GridLayout(3,2) );

pane.add(b1);
pane.add(b2);
pane.add(b3);
pane.add(b4);
pane.add(b5);
pane.add(b6);

jf.setDefaultCloseOperation(jf.EXIT_ON_CLOSE);
jf.setVisible(true);

}
}

The final product

We are done..for now

import javax.swing.*;
import java.awt.*;

public class MyGUI {

JLabel l1,l2;
JTextField tf1,tf2;
JButton b1,b2;

public static void main(String[] args) {

// TODO, add your application code
new MyGUI();
}

public MyGUI(){
JFrame jf=new JFrame();
jf.setTitle("My frame");
jf.setSize(500,300);

JLabel l1=new JLabel("label 1");
JLabel l2=new JLabel("label 2");

JTextField tf1=new JTextField(10);
JTextField tf2=new JTextField(5);

JButton b1=new JButton("Button 1");
JButton b2=new JButton("Button 2");

tf1.setText("i am a text field");

tf2.setText("i am a text field and can not be changed");
tf2.setEditable(false);

Container pane=jf.getContentPane();
pane.setLayout(new GridLayout(3,2) );

pane.add(l1);
pane.add(tf1);
pane.add(l2);
pane.add(tf2);
pane.add(b1);
pane.add(b2);

jf.setDefaultCloseOperation(jf.EXIT_ON_CLOSE);
jf.setVisible(true);

}
}

Useful resources for creating GUI's in Java

More help!

Some addition resources
The Swing Tutorial
This trail tells you how to create graphical user interfaces (GUIs) for applications and applets, using the Swing components.
Creating first GUI Java Program
Creating first GUI Java Program
Java: Creating Basic GUI
This is a short example of how to create a basic Swing gui application in Java. (The tip consists mainly of the code shown below.) This example demonstrates a border layout and uses buttons inside of panels to fill in the layout. To build an application from this, simply replace the buttons with gui components of your choosing.

You will notice a method is used to create and launch a frame. We do not extend JFrame. In theory, by n
How to Create a Swing GUI in Java
First, you need to know the basic java concepts of object and interface. We assume that you already know this - if no, you need to start from something like "how to learn java".

Great Stuff on Amazon

Loading

New Guestbook

  • Eddieraines Apr 19, 2012 @ 6:27 am | delete
    Good work. I have worked on Java and creating GUI's in it. Good tutorial that you have shared with us.

    Bounce Houses
  • jeffrichley Feb 24, 2012 @ 8:06 am | delete
    Good lens on starting Swing. So many people forget that it is there.

    What has your experience been delivering Swing apps into "the wild" where you can't control the version of Java on people's boxes?
  • 9yy4vw7k Jun 24, 2011 @ 4:17 am | delete
    dads ended up being skeptics and also Deists; people mainly expected your high-end administration which has an "unbreachable wall" amongst religious plus think; people sometimes written on the treaty together with the Moslem usa with Tripoli an apparent report this, compared with European union, a "United Suggests will not be, in different sensation, your Melinda usa. inches (So certainly perceived appeared to be a guideline with parting with religious plus think at that time the fact that treaty surpassed Congress which has no issue for this terms, plus Lead designer Sara Adams ok'd them right away, which has no fearfulness not wearing running shoes could jeopardize her politics long run. )Kobe VI
  • Sep 10, 2010 @ 9:31 am | delete
    Wow!
    I like your lens, very useful and inspiring. thank you.
    -----------------------------
    Panic Away Review
  • bentoboxuk Apr 24, 2010 @ 3:03 am | delete
    thanks for this lens, but everything I have tried does not work so far. Do I need to download a program first? Do I have to put this < symbol first ? I copied and pasted it, but only the text came up - I did not get any buttons or boxes.

by

aubrey_labuschagne

Hi. My name is Aubrey. I am lecturing JAVA, have my RHCT, web development, system administration, project  manager and have a hosting company.Visit... more »

Feeling creative? Create a Lens!