Java GUI | AWT Classes in Java | Event Handling

Java GUI is by far one of the most fun chapters in Java. I think you are going to enjoy it too, because hey I love it!

The primary reason being as humans we love to see our actions take form. What better way to see that when you do something and it takes shape quickly. Doesn’t it become a tad boring when all you do is type some code and except some numbers or words to show in your IDE’s output or console?

I say let something colossal happen. Like you creating a box that makes you feel good about yourself. Java GUI is that interactive part in Java that makes Java all the very much interesting. Because at the end of the day, it is all about the look and feel.

pretty ugly meme for java gui
GUI or Graphical User Interface is everything you see on your screen that allows you to interact in order to get something done. GUI is renowned for its ease of access, and making navigation a piece of cake. It forms the basis of every application nowadays.

The opposite of GUI is CUI which stands for Character User Interface that is entirely text based stuff. Which one would you prefer? Typing everything down on a keyboard to retrieve money, or simply use an ATM instead to withdraw it by clicking on some buttons? Latter? That’s what I thought.

In an MVC model, it is the view here that we are talking about that lets us have a peek at how our programming in the backend is going to make things appear in the front end.

What is AWT?

If you are hearing AWT for the first time, let me fill you in a little before we proceed. AWT stands for Abstract Window Toolkit. It is an API that allows you to develop Java GUI and other window-based applications in the programming language. It is a vast library that has tons of classes and methods that will make sure the job of creating Java GUI becomes really easy.

The components of AWT are platform dependent. Meaning that a particular window in Windows Operating System will look different when you run the same program in Mac Operating System.

AWT is considered to be heavyweight since its components make use of your operating system as you work on them. There are countless classes inside the AWT class which you could use to create a Java GUI application from scratch.

We are going to see a lot of examples here and have a lot of fun too learning about these classes.

So first let’s see what are the classes that we are going to see. A hierarchy diagram would be helpful:

AWT hierarchy in java

Component

Every operating system has its very own set of components. So even if you are opening an application like Paint it retains tons of components in it. Components like Menu, Buttons, Labels and containers etc.

Component Class is at the top of the hierarchy as you can see. Menu component is yet another component class that tends to everything menu related.

So that makes our component nothing but a graphical representation of everything that can be displayed on screens so that any end user could interact with it without any hassle.

Container

Container is simply a form of component that helps in containing other components like text field, buttons etc. It keeps tracks of components in the form of a list. The classes extending Container class are known as containers and its examples are Frame, Panel and Dialog.

Window

Window is a container that doesn’t have any borders or menu bars. It is nothing but a rectangular area displayed on screen. We can choose to run different programs in different windows. A Window Class creates a top level window.

You must use a frame, a dialog or another window to create a window.

Panel

Panel class is a concrete subclass of Container. There are no title bars, menu bars or borders here as well. You can have other components like button, lables, text field etc. though.

Frame

A Frame is a top level window that has borders and titles. It allows you to resize it. Most of the AWT applications in Java are created using Frame only. So it is something that you are going to use a lot.

There are two different constructors here that you can use:

  • Frame()
  • Frame(String title)

The second one will create a frame window with a predefined title.

Buttons, Labels, Checkboxes, List, Choices etc. are all components too, and we will see them as we proceed with examples.

Ways to Create a Frame

There are two ways you can create a frame. They are namely:

  • By Instantiating Frame Class
  • By Extending Frame Class

We will see both the methods of frame creation hereby by using an Example:

Let’s see to how to create a frame using instantiation:

import java.awt.*;

public class LearnAWT {
              LearnAWT() {
                        Frame f = new Frame("First Frame");
                        Label l = new Label("Look Mommy! I created a Frame today!");
                        Button b = new Button("Woohoo");
                        b.setBounds(200,250,70,30);
                        f.add(b);
                        f.add(l);
                        f.setSize(300,300);
                        f.setVisible(true);
                  }
public static void main(String []args) {
                  LearnAWT la = new LearnAWT();
        }
}

Notice how you need to import awt classes first. That’s the first thing you need to do before proceeding or your JVM wouldn’t get it.

Things to Remember

You can choose to write all the above code directly in the main() method itself, but think about it from the perspective of your end user. You are trying to hide stuff from him, right? They shouldn’t know much. Just give them a constructor that would be like a jar, application or a .exe file that they will run to open a program. (Isn’t that what all applications do after all?)

When you create a component you need add them one by one to the frame or they wouldn’t show. In the end, you need to make your frame visible by using the method setVisible(true) since a frame isn’t visible by default.

The setBounds() method of Component class will let you specify where you want your components located. Here the button parameters have been provided by filling up the following fields:

 setBounds(int xaxis, int yaxis, int width, int height)

Run the program and you will get a lovely frame looking at you:

frame example in java gui awt

You might have to close it by using your task manager. Now let’s create a frame using the second method. The “extends frame method” is simple as well.

Using Extends Frame

All we need to do is make our class extend the Frame class and that’s it. Here’s the code showing the same example. Since we are not using a constructor that has inbuilt title in it, we can opt to use Frame’s setTitle() method:

import java.awt.*;

public class LearnAWT extends Frame {
            LearnAWT() {
                    setTitle("First Frame");
                    Label l = new Label("Look Mommy! I created a Frame today!");
                    Button b = new Button("Woohoo");
                    setLayout(new FlowLayout());
                    add(b);
                    add(l);
                    setSize(300,300);
                    setVisible(true);
             }
public static void main(String []args) {
                   LearnAWT la = new LearnAWT();
            }
}

Notice here we have removed the button placement setBounds() method and used Container’s setLayout() method that takes LayoutManager’s instance as a parameter. It makes your frame carry a default layout that places every button in the center like this:

frame example 2

 

So cool to look at right?

Event Handling in Java GUI

Now as you might have noticed in the Java GUI example above, nothing happens when you click on the Button. Nothing happens when you are clicking on the cross button on your GUI window frame. Why is that?

That’s because we haven’t provided any job for them yet. Providing jobs for certain things to happen is basically what defines event handling. If you are changing the state of an object like clicking a button, or checking a box etc. all these activities are known as events.

It is the Event class in Java’s AWT package where all the classes and methods related to event handling are placed. There are tons of Event classes and Listener Interfaces (used to address an event) that comprise the topic of event handling.

How to Handle an Event

The first step to handle an event is to of course create a component. Then you need to register the component with a Listener. Since we are using a method of Listener interface we need to implement its respective Listener during class declaration.

So that takes us to the natural question – how do you register a component with a Listener?

You see every component has been provided an apt Listener method based upon their property. So for example:

Since a button’s property is related to an action (the pressing of a button) you find the following method tagged alongside:

addActionListener(ActionListener a)

The same goes for other components like:

  • MenuItem
  • TextField
  • List

Although TextField and List have two other frequently used methods named

  • addTextListener(TextListener t)
  • addItemListener(ItemListener i)

respectively. Checkbox and Choice components too use the addItemListener() method. TextArea uses just the addTextListener() method.

In our example above we will try to make something happen instead of leaving that Woohoo button stranded.

Other Things to Remember While Handling Event

Let us just make our button to do something hereby.

The first job would be to import java.awt.event.* class to import all classes that facilitate event handling.

Then type “implements ActionListener” against your class.

public class LearnAWT extends Frame implements ActionListener {

}

If you are working on an IDE it will automatically redden your Class Name saying that you need to implement the inherited abstract method actionPerformed(ActionEvent e) of the ActionListener interface.

But our first step should be to register our button against the ActionListener. Type the following in your code to make sure the button has been registered:

b.addActionListener(this);

where this helps to pass the current instance.

Example to Handle an Event

Now the next step would be to add the actionPerformed(ActionEvent e) code to our existing code. So now our whole code should look something like this:

import java.awt.*;
import java.awt.event.*;

public class LearnAWT extends Frame implements ActionListener {

Label l;
Button b;

                  LearnAWT() { 
                         setTitle("First Frame");
                         l = new Label("Look Mommy! I created a Frame  
                         b = new Button("Woohoo"); today!");
                         add(b); 
                         add(l); 
                         setLayout(new FlowLayout()); 
                         setSize(300,300); 
                         setVisible(true); 
                         b.addActionListener(this); 
                         } 
           public void actionPerformed(ActionEvent e) { 
                         b.setVisible(false); 
                         l.setText("Good Job Son!"); 
                        } 
           public static void main(String []args) { 
                        LearnAWT la = new LearnAWT(); 
         }
 }

I am trying to replace our existing label, with another text and making our current button disappear. So that’s the part of the code that will go in the actionPerformed() method.

Now if you will run the above program you will get the following result:

frame output result on clicking button awt

 

Another Example to Learn Event Handling

We will see this new Java GUI example by bringing to use our anonymous inner class learning. If you don’t remember please just flip back (click on the link).

Here we will create a button and a text field and make sure the text field gets populated with something when we click that button.

Here’s the code we should be writing:

import java.awt.*;
import java.awt.event.*;

public class LearnAWT extends Frame { 
TextField tf;
Button b;
             LearnAWT() { 
                    setTitle("First Frame"); 
                    tf = new TextField(); 
                    b = new Button("Woohoo"); 
                    b.setBounds(110,200,60,40); 
                    tf.setBounds(100, 100, 85, 20); 
                    add(b); 
                    add(tf); 
                    setLayout(null); 
                    setSize(300,300); 
                    setVisible(true); 

        b.addActionListener(new ActionListener(){ 
                public void actionPerformed(ActionEvent e) { 
                          tf.setText("Attaboy!");
                        } 
            }); 
          } 
public static void main(String []args) { 
           new LearnAWT(); 
         }
 }

Notice we have used setText() method of TextField Class to decide what goes inside the text box. If you run the above program you will get the following result:

frame text example result in java

Isn’t Anonymous Inner Class the better way of dealing with components? You drop actionListeners then and there! And you don’t have to create a separate class for that.

We will see a couple of dope Java GUI examples now that will make you fall in love with Java GUI AWT more.

Scottshak

Poet. Author. Blogger. Screenwriter. Director. Editor. Software Engineer. Author of "Songs of a Ruin" and proud owner of four websites and two production houses. Also, one of the geekiest Test Automation Engineers based in Ahmedabad.

You may also like...

3 Responses

  1. July 10, 2017

    […] of a website using Java GUI AWT hereby. Just bring all the knowledge that you had grasped about Java GUI AWT and the URL class to the table. That’s it! You will be […]

  2. July 11, 2017

    […] words. If you are coming here for the first time, just know that this chapter is a tributary of Java GUI AWT Classes in Java Chapter. You can go back and learn all the basics of AWT classes in […]

  3. August 22, 2018

    […] Yes the real action on how to make a video game for Android happens when you are allocating a field to listen for activities. Since we want some action to be performed when we click our Spin button, we need to tack it against a Listener. To understand what listeners are all about you can go back and refer to our Java Event Handling chapter. […]

Leave a Reply