Java Examples Explained

Home » 9. GUI » 9.5. Event handling » ActionEvent » Owl Greeting (GUI)

Owl Greeting (GUI)

Follow Java Examples Explained on WordPress.com

Categories

Receiving and processing input in the command line environment (shown in the Customised Hello  and Area of Rectangle examples) seems pretty straight forward. Interactions with users are accomplished through instructions or questions which are then followed by the user’s input. This makes the placing of statements to capture and process input to a program easy to do. In a GUI environment, however, users can interact with more than one GUI widget in any order they see fit. Therefore, handling this flexibility requires a little bit of work. In the following program, you will see how input from interaction with a widget is processed.

This example is presented in two stages. In the first stage, you will see how we display some GUI widgets. However, when you run the program, it will not respond to any of your interaction. You will see how your interaction is processed and responses are executed in the second stage.

Displaying GUI Widgets

Here is the program for the first stage:

1 | import javax.swing.JFrame;
2 | import java.awt.FlowLayout;
3 | import javax.swing.JLabel;
4 | import javax.swing.JTextField;
5 |
6 | public class OwlGreeting extends JFrame {
7 |    JLabel labelQuestion;
8 |    JTextField textAnswer;
9 |
10|    public OwlGreeting(){
11|      setLayout(new FlowLayout());
12|      labelQuestion = new JLabel("Whooooo's there?");
13|      textAnswer = new JTextField(10);
14|      add(labelQuestion);
15|      add(textAnswer);
16|    }
17|
18|    public static void main(String args[]){
19|      OwlGreeting window = new OwlGreeting();
20|      window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
21|      window.setSize(275, 100);
22|      window.setTitle("Owl Greeting");
23|      window.setVisible(true);
24|    }
25| }
The look and feel of the dialog you get depends on the computer you use to run the program. If you are using a Mac, this is what you see on screen after you compile and run the program:
owlGreeting1

Notice that we have extends JFrame after the class name (line 6). This makes our class, OwlGreeting, an extension of the JFrame class, which means it will behave like a JFrame, but with some additional features. In other words, you can add the functionality you need, while having all the necessary features of a JFrame window. This concept of extension is called inheritance. If you are interested, you can find out more about inheritance here. You might think this is a complicated way of using JFrame compared to the previous example. However, it is actually the standard way, because it allows a lot of flexibility in your program.

In this example, we use two GUI widgets: a label and a text field. The label is used to display a question and the text field is used to receive the user’s input. These two items are the additional features that you want to add to your class. Therefore, we need to declare them as class members of OwlGreeting. This is done by placing the declaration statements for these widgets in the beginning of the class, as shown on line 7-8.

We also need a constructor method (lines 10-16) which contains the statements that describe the process that we want to happen when an object of this class is created. On line 11, we set the layout manager as FlowLayout. On line 12 we create a label to display the question, and on line 13 we create a text field to allow users to type in the answer. Then, on lines 14-15 we add these two items to be displayed. Notice that the name of the constructor method is the same as the name of the class, and there is no keyword class in between public and the name of the method. This is how you declare a constructor method and differentiate it from other methods in the class (if any).

Although the constructor method is written before the main method, it does not mean that the statements inside it are executed before the statements in the main method. Always remember that the flow of execution of your program starts from the main method. Therefore, in this example, the first line to be executed is line 19. However, since line 19 invokes the creation of an object of the OwlGreeting class, which calls the constructor method described by lines 10-16, the next statement to be executed after line 19 is line 11. This is then followed by lines 12-15. Then, the flow of execution goes back to line 19, and the rest of the statements in the main method are executed.

Handling Input from GUI Widgets

In Java, responding to interactions with GUI widgets is accomplished through the process of handling events. Therefore, you need to first understand the general concept of event handling. Events are triggered by the system every time a user interacts with a GUI widget, for example, clicking the mouse or pressing a key. To process an event, we need an event listener. The role of an event listener is to listen for an event. Whenever an event is triggered, it will invoke its handler which will execute the responses as programmed.

Different GUI widgets trigger different types of events. Each type of event is listened for by its corresponding listener. A lot of events occur during the execution of a program. However we only need to handle the events that we are interested in. Therefore, you need to register an appropriate listener with a GUI widget. The type of listener depends on the type of event you are interested in. An event listener and its handler need to be implemented through a class. In other words, you need to have a class, and in this class you have a special method that implements the handler. This method needs to contain with statements that describe the responses you intend.

To summarise, we need to include the following actions in our program:

  • Implement the event listener using a class
  • Implement the associated handler inside the class
  • Register the event listener with the GUI widget that would trigger the event

Now, let’s see how we want the the program to respond. In this example, when the user enters a name in the text field and press , we want the program to display a greeting message. Assuming the user enters Fred and presses the key, the output will look like this:

greeting_answer

In this example, the event we are interested in is triggered when the user presses . This type of event is defined in a class called ActionEvent and the event listener associated with this event is called ActionListener. ActionListener has a method (or handler) called actionPerformed() which will be invoked when an ActionEvent is triggered. To register an ActionEvent with its listener, we need to call the addActionListener() method.

Here is the modified program:

1 | import javax.swing.JFrame;
2 | import javax.swing.JLabel;
3 | import java.awt.FlowLayout;
4 | import javax.swing.JTextField;
5 | import javax.swing.ImageIcon;
6 | import java.awt.event.ActionListener;
7 | import java.awt.event.ActionEvent;
8 |
9 | public class OwlGreeting extends JFrame implements ActionListener{
10|    JLabel labelQuestion, labelGreeting;
11|    JTextField textAnswer;
12|    ImageIcon owl;
13|
14|    public OwlGreeting(){
15|      setLayout(new FlowLayout());
16|      labelQuestion = new JLabel("Whooooo's there?");
17|      textAnswer = new JTextField(10);
18|      labelGreeting = new JLabel();
19|      owl = new ImageIcon("animal39-2.png");
20|      textAnswer.addActionListener(this);
21|      add(labelQuestion);
22|      add(textAnswer);
23|      add(labelGreeting);
24|    }
25|
26|    public static void main(String args[]){
27|      OwlGreeting window = new OwlGreeting();
28|      window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
29|      window.setSize(275, 100);
30|      window.setTitle("Owl Greeting");
31|      window.setVisible(true);
32|    }
33|
34|    public void actionPerformed(ActionEvent e){
35|      String name = textAnswer.getText();
36|      labelGreeting.setText("Hoot for " + name + "!");
37|      labelGreeting.setIcon(owl);
38|    }
39| }

The message is displayed in a label which contains some text preceeded by an image. Therefore, we need another label and an image icon. As shown on line 5, we add a statement to include the ImageIcon class. Then, on line 12, we declare owl as an object variable of ImageIcon, and on line 19 we create the object. Similarly, we declare labelGreeting as an object variable of JLabel, and on line 18, we create the object.

Both ActionEvent and ActionListener are defined in the java.awt.event package. Therefore, we add the statements on lines 6-7. As mentioned earlier, an event listener and its handler need to be implemented in a class; not necessarily a separate class, but a class. Therefore, since we are only handling one type of event, we will just use the class we have, the OwlGreeting class. Notice that on line 9, we have added the implements ActionListener. This means that not only does our OwlGreeting class work as a JFrame window, it also functions as an event listener. Consequently, we also added the description of a method called actionPerformed() as shown on lines 34-38. In this method, we have statements that will be executed when the user presses .

On line 20, we register textAnswer with the event listener by calling the addActionListener() method. The parameter this in this method refers to the object of a class that implements an ActionListener, which is the same object that calls the method. Hence the keyword this. You will find the this keyword used in many Java examples that use a similar concept of referring back to the object itself. If however you use a separate class to implement the event listener, you should replace it with the object variable of that class.

 

Icons made by Freepik from www.flaticon.com is licensed by CC BY 3.0
Advertisement

1 Comment

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 )

Connecting to %s

%d bloggers like this: